Adding rows programmatically to a grid in a WPF window
I have a window with a button and a grid in this window with row and column settings. I am trying to create a button that, when clicked, will add another row to the Grid and then assign a custom control to that row.
I found several ways to do this online for datagrids, but added nothing to define the rowdefinition for the grid. Can anyone help with the code for this?
WPF:
<DockPanel>
<Button DockPanel.Dock="Top" Height="22" x:Name="AddRow" Click="AddRow_Click">
<TextBlock Text="Add Skill"/>
</Button>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="1"/>
<ColumnDefinition Width="1"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1"/>
</Grid.RowDefinitions>
</Grid>
</DockPanel>
+3
source to share
1 answer
It shouldn't be too difficult. I'll just illustrate the use of the code for simplicity.
<Grid x:Name="TheGrid">
<Grid.RowDefinitions>
<RowDefinition Height="1"/>
</Grid.RowDefinitions>
</Grid>
In the button click handler:
TheGrid.RowDefinitions.Add(new RowDefinition());
Then just add your custom control to the grid and assign a line number to it.
var uc = new MyUserControl();
TheGrid.Children.Add(uc);
Grid.SetRow(uc, TheGrid.RowDefinitions.Count - 1);
+4
source to share