在 XAML 中,我创建了一个这样的按钮:
<Button MouseEnter="Button_MouseEnter">
<Button.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="asd"/>
<Label Grid.Row="1" Content="xxx"/>
<Label Grid.Row="2" Content="yyy"/>
</Grid>
</Button.Content>
</Button>
现在我需要在代码隐藏中访问 Button 内容中的其中一个控件。假设我需要一个 TextBlock。
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button button = (Button)sender;
// ?
}
我该怎么做? 我还有多个像这样的按钮通过数据绑定(bind)自动创建。 我需要访问这些控件的原因是我想在特定情况下为其中之一设置动画。
最佳答案
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
TextBox textBox = null;
if (b != null)
{
foreach (var frameworkElement in ((Grid)b.Content).Children)
{
if (frameworkElement is TextBox)
{
textBox = (TextBox)frameworkElement;
break;
}
}
}
}
这只是为了说明如何提取作为按钮内容的 Grid 的子项。我希望这会帮助您了解这个想法。
关于c# - 如何在代码隐藏中访问 Button.Content 中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645314/