【问题标题】:Access TextBlock.Text Inside a Button访问按钮内的 TextBlock.Text
【发布时间】:2016-08-02 22:28:21
【问题描述】:

我有一组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++;
    }
}   

但我无法访问TextBlock (NullException)。当 Button 内的 Textblock's 文本属性以编程方式访问时,如何访问它?

【问题讨论】:

  • 我认为问题是((control as Button).Content).Children你可能需要这个((control as Button).Content) as TextBlock)

标签: c# wpf xaml user-interface button


【解决方案1】:

使用var tb = ((control as Button).Content as TextBlock); 而不是(control as Button).Content).Children.OfType&lt;TextBlock&gt;().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++;
    }
}  

【讨论】:

    【解决方案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++;
        }
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-12
      相关资源
      最近更新 更多