visc visc - 27 days ago 10
C# Question

Get TextBlock inside Button

I have a

Button
with a
TextBlock
embedded inside. When the
Button
is clicked, I want to be able to fetch the
TextBlock
inside it and modify it's members.

Here is how my button is setup:

<Button Click="Select_Click" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Padding="0,20,20,20">
<TextBlock Text="My text" FontSize="20" Style="{StaticResource TextBlockStyle}"/>
</Button>


In my code behind I want to be able to access the embedded
TextBlock
:

public void Select_Click(object sender, RoutedEventArgs e)
{
// Get the `TextBlock` from `sender` here
}


I've taken a look at the visual tree of the
Button
but I'm not seeing the
TextBlock
. I called
GetVisualChildren()
on the
Button
but I only see a
Grid
and no way to get to the
Textblock
.

Answer Source

The content of the Button is stored in its Content property and in your case, the TextBlock is the content of the Button.

public void Select_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    TextBlock textBlock = (TextBlock)button.Content;
}