Search code examples
c#wpfcastingtextblock

Casting Control to TextBlock in a Grid


I have a set of TextBlocks inside a Grid that I would like to be able to programatically access their .Text properties. There are also Buttons and Images inside the Grid, so I've done some validation like so;

foreach (Control control in navButtonGrid.Children)
{
    if (control.GetType() == typeof(TextBlock))
    {
        //TextBlock.Text here
    }
}

In doing this I get an error,

Cannot convert type 'System.Windows.Controls.Control' to 'System.Windows.Controls.TextBlock' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

How am I able to correctly cast my Control so that I can access only the TextBlocks in the Grid?

FINAL EDIT: I have all of the TextBlock.Text inside the Buttons being named, however they are all the same Text. This is my implementation;

int i = 0;
foreach (DataRow row in navButtonDT.Rows)
{
    foreach (UIElement control in navButtonGrid.Children)
    {
        if (control.GetType() == typeof(Button))
        {
            TextBlock tb = ((control as Button).Content as StackPanel).Children.OfType<TextBlock>().FirstOrDefault();
            tb.Text = navButtonDT.Rows[i][1].ToString();
        }
    }
    i++;
}

If I do this all the TextBlocks take the string value of the last DataRow. What I would like is that TextBlock1.Text = row1, TextBlock2.Text = row2 etc etc..


Solution

  • Simply use OfType like this:

    foreach (var control in navButtonGrid.Children.OfType<TextBlock>())
    {
        //Do your stuff with control      
    }
    

    Or you could replace the Control with var or UIElement in foreach:

    foreach (var control in navButtonGrid.Children)
    {
        if (control.GetType() == typeof(TextBlock))
        {
             TextBlock tb = control as TextBlock;
        }
    }
    

    Or:

    foreach (UIElement control in navButtonGrid.Children)
    {
        if (control.GetType() == typeof(TextBlock))
        {
            TextBlock tb = control as TextBlock;
        }
    }
    

    EDIT: To find a TextBlock inside a Button you could do like this:

    else if (control.GetType() == typeof(Button))
    {
        TextBlock tb = ((control as Button).Content as StackPanel).Children.OfType<TextBlock>().FirstOrDefault();
    }