如何通过绑定将 RowDefinition 或 ColumnDefinition 动态添加到 Grid? [英] How to dynamically add RowDefinition or ColumnDefinition to a Grid with binding?
问题描述
我正在尝试创建一个具有可变行数和列数的表.我使用 ItemsControl
来执行此操作,该 Grid
作为其 ItemsPanel
.而且我知道我可以通过 ItemContainerStyle
设置每个项目的 Grid.Row
和 Grid.Column
.但是当我无法通过名称访问 Grid 时,我不知道如何更改行数和列数及其大小.
I'm trying to create a table with a variable number of rows and columns. I'm doing this with an ItemsControl
which has a Grid
as its ItemsPanel
. And I know I can set Grid.Row
and Grid.Column
of each item through its ItemContainerStyle
. But I don't know how to change the number of rows and columns and their sizes when I can't access the Grid by its name.
如何在运行时修改 Grid
的 RowDefinitions
或 ColumnDefinitions
无需任何代码隐藏使用绑定?
How can you modify RowDefinitions
or ColumnDefinitions
of a Grid
in run-time without any code-behind using Binding?
这是 XAML 代码:
This is the XAML code:
<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
内.
I tried to add some RowDefinition
in code behind but I couldn't find a way to gain access to myGrid
by its name (or any other way) since it is inside an ItemsPanelTemplate
.
我想知道是否有任何方法可以在运行时以编程方式添加或修改RowDefinitions
?
I'm wondering if is there any way to programmatically add or modify RowDefinitions
in run-time?
推荐答案
你可以使用 附加属性用于在设置或更改这些属性时修改 RowDefinitions
和 ColumnDefinitions
的 Grid
.
You can use attached properties for a Grid
that modify the RowDefinitions
and ColumnDefinitions
when those properties are set or changed.
它将允许您像这样编写 Grid
:
It will allow you to write your Grid
like this:
<Grid local:GridHelpers.RowCount="{Binding MaxGridRow}"
local:GridHelpers.ColumnCount="3" />
然后只需从您的 ViewModel
公开一个属性,该属性返回 Cells
集合中的最大行号.
Then just expose a property from your ViewModel
which returns the largest row number in the Cells
collection.
您可以找到这些属性的详细实现在我的博客上.
You can find a detailed implementation of those properties on my blog.
这篇关于如何通过绑定将 RowDefinition 或 ColumnDefinition 动态添加到 Grid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!