简体   繁体   中英

Access TextBlock.Text Inside a Button

I have a set of Buttons that are styled as so;

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

I want to loop through these Buttons and modify the TextBlock.Text inside them. So far I have done something like this;

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++;
    }
}   

But I am having no luck in accessing the TextBlock ( NullException ). How can I access the Textblock's text property when it inside the Button programtically?

Since the TextBlock is placed inside your button as content directly and you don't use any Container Controls like StackPanel you don't need to use Children . Just use this:

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++;
    }
}   

Use var tb = ((control as Button).Content as TextBlock); instead of (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++;
    }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM