[英]Get TextBlock inside Button
I have a Button
with a TextBlock
embedded inside. 我有一个嵌入了TextBlock
的Button
。 When the Button
is clicked, I want to be able to fetch the TextBlock
inside it and modify it's members. 单击Button
,我希望能够获取其中的TextBlock
并修改其成员。
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
: 在后面的代码中,我希望能够访问嵌入式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
. 我看了一下Button
的可视树,但没有看到TextBlock
。 I called GetVisualChildren()
on the Button
but I only see a Grid
and no way to get to the Textblock
. 我在Button
上调用了GetVisualChildren()
,但我只看到一个Grid
而无法访问Textblock
。
The content of the Button
is stored in its Content
property and in your case, the TextBlock
is the content of the Button
. Button
的内容存储在其Content
属性中,在您的情况下, TextBlock
是Button
的内容。
public void Select_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
TextBlock textBlock = (TextBlock)button.Content;
}
Just do some casting and it's pretty simple 只是做一些转换,这很简单
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Establish_handlers();
}
void Establish_handlers()
{
Mybutton.Click += Mybutton_Click;
}
private void Mybutton_Click(object sender, RoutedEventArgs e)
{
Button clicked_button = (Button)sender;
TextBlock desired_text = (TextBlock)clicked_button.Content;
Textbox_Show_Button_Content.Text = desired_text.Text;
}
}
<StackPanel>
<Button x:Name="Mybutton">
<TextBlock>Hello</TextBlock>
</Button>
<TextBox x:Name="Textbox_Show_Button_Content"></TextBox>
</StackPanel>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.