WPF Grid 作为 ItemsPanel 用于动态绑定到 ItemsControl 的列表 [英] WPF Grid as ItemsPanel for a list dynamically bound to an ItemsControl
问题描述
我将 Grid 用作 ItemsPanel,用于动态绑定到 ItemsControl 的列表.下面的代码正在运行 - 还有一个问题:我找不到动态初始化网格的 ColumnDefinitions 和 RowDefinitions 的方法.因此,所有值都被置于彼此之上.
I am using a Grid as ItemsPanel for a list dynamically bound to an ItemsControl. The code below is working - with a remaining problem: I can’t find a way to dynamically initialize the ColumnDefinitions and RowDefinitions of the grid. As consequence all values are placed on top of each other.
<ItemsControl ItemsSource="{Binding Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
请注意,我正在根据 MVVM 模式搜索答案.因此,子类化和后面的代码只是变通方法,而不是解决方案.
Please be aware, that I am searching an answer according the MVVM pattern. Therefore sub classing and code behind are just workarounds, but no solutions.
推荐答案
你需要一些方法来告诉 Grid 它有多少行/列.也许在加载每个项目时,您可以检查 RowIndex
和 ColumnIndex
的值,并在需要时将行/列添加到网格.
You'll need some way to tell the Grid how many Rows/Columns it has. Perhaps as each Item loads you could check the value of RowIndex
and ColumnIndex
and add Rows/Columns to the Grid if needed.
作为另一种选择,也许您可以在 ViewModel 中公开 RowCount
和 ColumnCount
属性,它们返回最大 RowIndex
和 ColumnIndex
,然后在 Grid 的 Loaded 事件中添加您需要的任意数量的列/行.
As another alternative, perhaps you can expose RowCount
and ColumnCount
properties in your ViewModel that return the max RowIndex
and ColumnIndex
, and in the Grid's Loaded event add however many Columns/Rows you need.
如果代码仅与 UI 相关,我发现在 MVVM 中使用代码隐藏是完全可以接受的.
I find it perfectly acceptable to use code-behind in MVVM IF the code is related to the UI only.
另一个想法是将代码隐藏中的项目排列到二维网格中,然后将其返回到视图,然后将该网格绑定到具有 AutoGenerateColumns=True
的 DataGrid 并删除标题
Another idea would be to arrange your items in your code-behind into a 2D grid before returning it to the View, and then bind that Grid to a DataGrid with AutoGenerateColumns=True
and the headers removed
更新
我目前对这个问题的解决方案是为 Grid
使用一组 AttachedProperties
,允许您绑定 RowCount
和 ColumnCount
属性到 ViewModel 上的属性
My current solution to this problem is to use a set of AttachedProperties
for a Grid
that allow you to bind RowCount
and ColumnCount
properties to a property on the ViewModel
您可以在我的博客 这里,它们可以这样使用:
You can find the code for my version of the attached properties on my blog here, and they can be used like this:
<ItemsPanelTemplate>
<Grid local:GridHelpers.RowCount="{Binding RowCount}"
local:GridHelpers.ColumnCount="{Binding ColumnCount}" />
</ItemsPanelTemplate>
这篇关于WPF Grid 作为 ItemsPanel 用于动态绑定到 ItemsControl 的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!