如何使用绑定动态地将RowDefinition或ColumnDefinition添加到Grid?

时间:2012-01-25 09:45:49

标签: wpf templates grid itemscontrol

我正在尝试创建一个包含可变行数和列数的表。我使用的ItemsControl Grid作为其ItemsPanel来执行此操作。我知道我可以通过Grid.Row设置每个项目的Grid.ColumnItemContainerStyle。但是当我无法通过名称访问网格时,我不知道如何更改行数和列数及其大小


问题:

如何仅使用 XAML 绑定,在运行时修改RowDefinitionsColumnDefinitions Grid强>没有代码隐藏?


这是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的方法,因为它位于{{1 }}

我想知道是否有任何方式以编程方式在运行时添加或修改ItemsPanelTemplate

2 个答案:

答案 0 :(得分:27)

您可以Grid使用RowDefinitions修改ColumnDefinitionsGrid,当设置或更改这些属性时。

它允许您像这样写<Grid local:GridHelpers.RowCount="{Binding MaxGridRow}" local:GridHelpers.ColumnCount="3" />

ViewModel

然后只显示Cells中的一个属性,该属性返回{{1}}集合中最大的行号。

您可以找到这些属性的详细实现attached properties

答案 1 :(得分:9)

如果您可以从代码隐藏中访问网格,则可以执行以下操作:

var rowDefinition = new RowDefinition();
rowDefinition.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowDefinition);