我有一组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
)。如何在Textblock's
程序中访问Button
文本属性?
答案 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++;
}
}