Tutorial: How to Programmatically Add Rows to a XAML Grid
Example Markup
<Grid Name="MyGrid">
</Grid>
Code Behind
//declare variables
RowDefinition RowDef;
StackPanel StackP;
TextBlock TextB;
//Add 10 rows to Grid
for (int i = 0; i < 10; i++)
{
//Define new Row to add
RowDef = new RowDefinition();
RowDef.Height = new GridLength(100);
//Add row definition to Grid
MyGrid.RowDefinitions.Add(RowDef);
//Define the control that will be added to new row
TextB = new TextBlock();
TextB.Text = "Row: " + i.ToString();
//create stackpanel and define which row to add the stackpanel to
StackP = new StackPanel();
StackP.SetValue(Grid.RowProperty, i);
//add your control to the stackpanel
StackP.Children.Add(TextB);
//add the stackpanel to the grid
MyGrid.Children.Add(StackP);
}
Published: June 30, 2011