gpt4 book ai didi

WPF Grid 作为 ItemsPanel 用于动态绑定(bind)到 ItemsControl 的列表

转载 作者:行者123 更新时间:2023-12-03 23:17:52 27 4
gpt4 key购买 nike

对于动态绑定(bind)到 ItemsControl 的列表,我使用 Grid 作为 ItemsPanel。下面的代码正在运行 - 还有一个问题:我找不到动态初始化网格的 ColumnDefinitions 和 RowDefinitions 的方法。因此,所有值都放在彼此之上。

<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 模式搜索答案。因此,子类化和后面的代码只是解决方法,但没有解决方案。

最佳答案

您需要一些方法来告诉网格它有多少行/列。也许在加载每个项目时,您可以检查 RowIndex 的值。和 ColumnIndex如果需要,将行/列添加到网格中。

作为另一种选择,也许您可​​以公开 RowCountColumnCount ViewModel 中返​​回最大值 RowIndex 的属性和 ColumnIndex ,并在 Grid 的 Loaded 事件中添加您需要的许多列/行。

如果代码仅与 UI 相关,我发现在 MVVM 中使用代码隐藏是完全可以接受的。

另一个想法是将代码隐藏中的项目排列到二维网格中,然后将其返回到 View ,然后将该网格绑定(bind)到具有 AutoGenerateColumns=True 的 DataGrid并删除了标题

更新

我目前对这个问题的解决方案是使用一组 AttachedProperties对于 Grid允许您绑定(bind)RowCountColumnCount属性到 ViewModel 上的属性

您可以在我的博客 here 上找到我的附加属性版本的代码。 ,它们可以像这样使用:

<ItemsPanelTemplate>
<Grid local:GridHelpers.RowCount="{Binding RowCount}"
local:GridHelpers.ColumnCount="{Binding ColumnCount}" />
</ItemsPanelTemplate>

关于WPF Grid 作为 ItemsPanel 用于动态绑定(bind)到 ItemsControl 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6995844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com