13
votes

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>
1
What speaks against using a DataGrid, or a ListView using GridView? Why do you insist on a Grid? Note that DataGrid and ListView are specifically meant to display a collection of data/content/things, whereas a Grid is merely meant to layout UI elements...user2819245
I'm going to assign a user control to each row in the grid and each user control assignment will be identical but give the user adding it the ability to subscribe to a different data feed. so instead of opening multiple windows to see multiple data feeds they can see them all in rows in one window.mrcavanaugh09
Then use a ListView with a GridView as its view. The ListView will display a collection of objects. Those objects are of a type/class you would define and which represent one data feed. Define columns for the GridView so that the DisplayMemberBinding property of each column is bound to each data feed object.user2819245
Thanks. Your idea to use a list view also worked. I've went with the answer below because it follows the same pattern I've been using on my other windows.mrcavanaugh09

1 Answers

29
votes

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);