如何使用绑定动态地向网格(Grid)添加行定义(RowDefinition)或列定义(ColumnDefinition)?

14
我试图创建一个可变行数和列数的表格。我使用了一个带有Grid作为其ItemsPanelItemsControl。我知道可以通过其ItemContainerStyle设置每个项的Grid.RowGrid.Column。但是当我无法通过名称访问Grid时,我不知道如何更改行数、列数及其大小

问题:

如何使用绑定在运行时修改GridRowDefinitionsColumnDefinitions,并且不需要任何代码后台?

以下是XAML代码:

<ItemsControl Name="myItemsControl" ItemsSource="{Binding Cells}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid Name="myGrid">

                <Grid.RowDefinitions>
                    <!-- unknown number of rows are added here in run-time -->
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <!-- known number of columns are added here in run-time -->
                </Grid.ColumnDefinitions>

            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style.../>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>
我试图在代码后端添加一些RowDefinition,但我找不到以其名称(或其他任何方式)访问myGrid的方法,因为它位于ItemsPanelTemplate内。
我想知道是否有办法在运行时通过编程方式添加或修改RowDefinitions
2个回答

31
你可以使用附加属性来修改GridRowDefinitionsColumnDefinitions。当这些属性被设置或修改时,它们会发挥作用。
这将使您的Grid编写起来更加简单:
<Grid local:GridHelpers.RowCount="{Binding MaxGridRow}"
      local:GridHelpers.ColumnCount="3" />
然后,只需从您的ViewModel公开一个属性,该属性返回Cells集合中最大的行号。
您可以在我的博客上找到这些属性的详细实现。 链接

非常感谢,我感到放心:) 顺便说一下,最后两个方法中有一个小错误。我将它们改为:GetStarColumns(grid).Split(','); - Bizhan
@Bizz 谢谢 :) 第一次将代码复制到WordPress时,它会删除所有特殊字符,我可能错误地用双引号替换了单引号。额外的.ToString()是因为星形列/行以前是整数,后来有一天我需要多个星形列,决定将其更新为字符串。 - Rachel
如何在XAML中定义本地变量? - arun d
通常在<Window>标签中会出现类似于xmlns:local="clr-namespace:MyProjectNamespace"的内容。它告诉WPF使用术语“local”作为指向XML命名空间MyProjectNamespace的快捷方式。 - Rachel
1
感谢更新,@Rachel。我已经使用了UniformGrid而不是Grid,并绑定了行。[链接]http://stackoverflow.com/questions/43627127/bind-dynamically-number-of-rowdefinition-to-a-grid-in-an-itemspaneltemplate?noredirect=1#comment74311216_43627127 - arun d

9
如果您可以从代码后台访问网格,则可以执行以下操作:
var rowDefinition = new RowDefinition();
rowDefinition.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowDefinition);

这并没有帮助。我无法通过名称从代码内部访问myGrid - Bizhan
1
whatever it is是ItemsControl的ItemPanelTemplate时,您无法访问它。@WtFudgE,您可能正在做其他事情。 - Xavier Huppé

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接