wpf 如何使用绑定将 RowDefinition 或 ColumnDefinition 动态添加到网格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9000549/
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
How to dynamically add RowDefinition or ColumnDefinition to a Grid with binding?
提问by Bizhan
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 sizeswhen I can't access the Grid by its name.
我正在尝试创建一个具有可变行数和列数的表。我正在用ItemsControl
aGrid
作为它的ItemsPanel
. 我知道我可以设置Grid.Row
和Grid.Column
每个项目通过的ItemContainerStyle
。但是当我无法通过名称访问 Grid 时,我不知道如何更改行数和列数及其大小。
Question:
题:
How can you modify RowDefinitions
or ColumnDefinitions
of a Grid
in run-time without any code-behindusing Binding?
你如何修改RowDefinitions
或ColumnDefinitions
的Grid
在运行时无需任何代码隐藏使用绑定?
This is the XAML code:
这是 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>
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
.
我试图RowDefinition
在后面的代码中添加一些,但我找不到myGrid
通过其名称(或任何其他方式)访问的方法,因为它位于ItemsPanelTemplate
.
I'm wondering if is there any way to programmatically add or modify RowDefinitions
in run-time?
我想知道是否有任何方法可以在运行时以编程方式添加或修改RowDefinitions
?
回答by Rachel
You can use attached propertiesfor a Grid
that modify the RowDefinitions
and ColumnDefinitions
when those properties are set or changed.
您可以使用附加属性来Grid
修改这些属性RowDefinitions
以及ColumnDefinitions
何时设置或更改这些属性。
It will allow you to write your Grid
like this:
它将允许您Grid
像这样写:
<Grid local:GridHelpers.RowCount="{Binding MaxGridRow}"
local:GridHelpers.ColumnCount="3" />
Then just expose a property from your ViewModel
which returns the largest row number in the Cells
collection.
然后从您的属性中公开一个属性,ViewModel
该属性返回Cells
集合中的最大行号。
You can find a detailed implementation of those properties on my blog.
您可以在我的博客上找到这些属性的详细实现。
回答by Y.Yanavichus
If you had access to the grid from code-behind you could do this:
如果您可以从代码隐藏访问网格,则可以执行以下操作:
var rowDefinition = new RowDefinition();
rowDefinition.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowDefinition);