我正在尝试创建一个包含可变行数和列数的表。我使用的ItemsControl
Grid
作为其ItemsPanel
来执行此操作。我知道我可以通过Grid.Row
设置每个项目的Grid.Column
和ItemContainerStyle
。但是当我无法通过名称访问网格时,我不知道如何更改行数和列数及其大小。
如何仅使用 XAML 和绑定,在运行时修改RowDefinitions
或ColumnDefinitions
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
?
答案 0 :(得分:27)
您可以Grid
使用RowDefinitions
修改ColumnDefinitions
和Grid
,当设置或更改这些属性时。
它允许您像这样写<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);