Based on the answer to SO question "[WPF: arranging collection items in a grid](https://stackoverflow.com/questions/3798739/wpf-arranging-collection-items-in-a-grid)", I have the following:

> 
> 
> ```
>     <ItemsControl Name="itemsControl1" ItemsSource="{Binding MyItems}">
>         <ItemsControl.ItemsPanel>
>             <ItemsPanelTemplate>
>                 <Grid Name="theGrid" ShowGridLines="True" />
>             </ItemsPanelTemplate>
>         </ItemsControl.ItemsPanel>
>         <ItemsControl.ItemContainerStyle>
>             <Style TargetType="{x:Type FrameworkElement}">
>                 <Setter Property="Grid.Row" Value="{Binding RowIndex}" />
>                 <Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
>             </Style>
>         </ItemsControl.ItemContainerStyle>
>     </ItemsControl>
> 
> ```
> 
> 

Now, I want to set the number of rows and columns of theGrid in the code behind:

```
            theGrid.RowDefinitions.Clear();
            theGrid.ColumnDefinitions.Clear();

            for (uint i = 0; i < theNumberOfRows; i++)
                theGrid.RowDefinitions.Add(new RowDefinition());

            for (uint i = 0; i < theNumberOfCols; i++)
                theGrid.ColumnDefinitions.Add(new ColumnDefinition());

```

For this, of course, I need to find the grid. I've used CrimsonX's FindChild in SO question [WPF ways to find controls](https://stackoverflow.com/questions/636383/wpf-ways-to-find-controls) to first locate itemsControl1 and then, using it as the parent, locate theGrid.

```
    Grid FindTheGrid()
    {

            ItemsControl ic = (ItemsControl)this.FindName("itemsControl1");
            Grid theGrid = FindChild<Grid>(ic, "theGrid");

    }

```

This works when called from a button's click event handler. It fails, however, when called from MainWindow's constructor because ic's childrenCount is 0.

```
int childrenCount = VisualTreeHelper.GetChildrenCount(theParent);

```

So, how can I set theGrid's row and column collections before the window is shown to the user?