访问Button内的TextBlock.Text

时间:2016-04-12 10:50:48

标签: c# wpf xaml user-interface button

我有一组Buttons,其风格如此;

<Button x:Name="rhsNavButton1">
    <TextBlock TextWrapping="Wrap" TextAlignment="Center"/>
</Button>

我想循环浏览这些Buttons并修改其中的TextBlock.Text。到目前为止,我做过类似的事情;

int j = 11;
foreach (UIElement control in RHSNavButtonGrid.Children)
{
    if (control.GetType() == typeof(Button))
    {
        var tb = ((control as Button).Content).Children.OfType<TextBlock>().FirstOrDefault();
        tb.Text = buttonNames.Rows[j][0].ToString();
        j++;
    }
}   

但我没有运气访问TextBlockNullException)。如何在Textblock's程序中访问Button文本属性?

2 个答案:

答案 0 :(得分:2)

由于TextBlock作为内容直接放在您的按钮内,并且您不使用任何Container Controls StackPanel,因此您不需要使用Children }}。只需使用:

int j = 11;
foreach (UIElement control in RHSNavButtonGrid.Children)
{
    if (control.GetType() == typeof(Button))
    {
        var tb = ((control as Button).Content) as TextBlock;
        tb.Text = buttonNames.Rows[j][0].ToString();
        j++;
    }
}   

答案 1 :(得分:2)

使用var tb = ((control as Button).Content as TextBlock);代替(control as Button).Content).Children.OfType<TextBlock>().FirstOrDefault();

int j = 11;
foreach (UIElement control in RHSNavButtonGrid.Children)
{
    if (control.GetType() == typeof(Button))
    {
        var tb = ((control as Button).Content  as TextBlock);
        tb.Text = buttonNames.Rows[j][0].ToString();
        j++;
    }
}