How to dynamically add RowDefinition or ColumnDefinition to a Grid with binding?

Question:

How can you change RowDefinitions or ColumnDefinitions Grid at runtime using only XAML and codeless binding ?


I have an ItemsControl element that shows its elements in a Grid , this Grid has dynamic RowDefinitions as follows:

 <ItemsControl Name="myItemsControl" ItemsSource="{Binding Cells}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid Name="myGrid"> <Grid.RowDefinitions> <!-- unknown number of rows are added here in run-time --> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <!-- known number of columns are added here in run-time --> </Grid.ColumnDefinitions> </Grid> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style.../> </ItemsControl.ItemContainerStyle> </ItemsControl> 

I tried adding the RowDefinition code to the code behind, but I could not find a way to access myGrid since it is inside myGrid ItemsPanelTemplate .

I am wondering if there is a way to programmatically add or change RowDefinitions at runtime ?

+9
source share
3 answers

You can use the attached properties for the Grid , which change the RowDefinitions and ColumnDefinitions when these properties are set or changed.

This will allow you to write your Grid as follows:

 <Grid local:GridHelpers.RowCount="{Binding MaxGridRow}" local:GridHelpers.ColumnCount="3" /> 

Then simply derive a property from your ViewModel that returns the largest number of rows in the Cells collection.

A detailed implementation of these properties can be found on my blog .

+25
source

If you had access to the grid from code, you could do this:

 var rowDefinition = new RowDefinition(); rowDefinition.Height = GridLength.Auto; grid.RowDefinitions.Add(rowDefinition); 
+9
source

Just use myItemsControl.GetTemplatedChild("myGrid") insted. In addition, you must boot before you can start using the expression above.

-one
source

All Articles