在 WPF 窗口中以编程方式向网格添加行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43769618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:04:52  来源:igfitidea点击:

adding rows programmatically to grid in WPF window

c#wpf

提问by mrcavanaugh09

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:

到目前为止的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>

回答by McGarnagle

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