WPF 网格作为动态绑定到 ItemsControl 的列表的 ItemsPanel [英] WPF Grid as ItemsPanel for a list dynamically bound to an ItemsControl
问题描述
我使用网格作为动态绑定到 ItemsControl 的列表的 ItemsPanel.下面的代码正在工作 - 还有一个问题:我找不到动态初始化网格的 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.
推荐答案
您需要某种方式来告诉网格它有多少行/列.也许当每个项目加载时,您可以检查 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.
另一个想法是在将代码隐藏中的项目返回到视图之前将其排列到 2D 网格中,然后将该网格绑定到具有 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
更新
我目前对这个问题的解决方案是使用一组 AttachedProperties
作为 Grid
允许您绑定 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 网格作为动态绑定到 ItemsControl 的列表的 ItemsPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!