❔ System.InvalidCast Exception when looping through Controls.Grid.Children

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.Button' to type 'System.Windows.Controls.UIElementCollection'.'

trying to programatically add buttons to a grid, but I'm getting this error when looping through the grids children.


this is where I'm looping through it
private void addGameToView(Game game)
{
    Button button = new Button();
    if (game.Icon == null)
    {
        button.Content = game.Name;

        if (gamesGrid.Children.Count > 0) {
            foreach (UIElementCollection child in gamesGrid.Children) //ERROR HERE
            {
                foreach (UIElement element in child)
                {
                    Debug.Write(element.ToString());
                    if (child.GetType() != typeof(Game))
                    {
                        //Grid.SetColumn(button, Grid.GetColumn(element));
                        //Grid.SetRow(button, Grid.GetRow(element));
                        //gamesGrid.Children.Add(button);
                        //break;
                    }
                }
            }
        } else
        {
            Grid.SetColumn(button, 0);
            Grid.SetRow(button, 0);
            gamesGrid.Children.Add(button);
        }
    }
}


this is the XAML defining the rows & columns
<Grid Name="gamesGrid" Grid.Row="0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
</Grid>
Was this page helpful?