Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding rows programmatically to grid in WPF window

Tags:

c#

wpf

I have a window with a button and a Grid in this window with rows and columns setup. I'm trying to create a button that when clicked will add another row to the Grid and then assign a user control to that row.

I've found a bunch of ways to do this online to datagrids but nothing for adding a rowdefinition to a grid. Can anyone assist with the code for this?

WPF so far:

<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>
like image 847
mrcavanaugh09 Avatar asked May 03 '17 20:05

mrcavanaugh09


1 Answers

That shouldn't be too difficult. I'll illustrate using code-behind for simplicity's sake.

<Grid x:Name="TheGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="1"/>  
    </Grid.RowDefinitions>
</Grid>  

In the button's click handler:

TheGrid.RowDefinitions.Add(new RowDefinition());

Then just add your user control to the grid, and assign it the row number.

var uc = new MyUserControl();
TheGrid.Children.Add(uc);
Grid.SetRow(uc, TheGrid.RowDefinitions.Count - 1);
like image 173
McGarnagle Avatar answered Sep 23 '22 01:09

McGarnagle