您可以使用将ItemsPanel 设置为Grid 或UniformGrid 的ItemsControl 来显示您的收藏。我有一些 ItemsControl 示例 here 可能会对您有所帮助,因为我不认为 MDSN 的示例很有帮助。
如果您可以将Rows 和Columns 属性绑定到ViewModel 中的属性,那么UniformGrid 将是最简单的,但是这要求您的所有单元格大小相同,我不记得是否Rows 和 Columns 属性是参与或不参与绑定系统的 DependencyProperties。
<ItemsControl ItemsSource="{Binding MyCollection}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding ColumnCount}"
Rows="{Binding RowCount}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
如果这对您不起作用,您可以使用Grid 作为ItemsPanel,并在ItemContainerStyle 中设置Grid.Row 和Grid.Column 绑定。
这将要求您在ObservableCollection 中的每个单元格对象上都有属性来说明该单元格所在的行/列,但是我怀疑您无论如何都需要这些来确定单击命令中的相邻单元格等内容.
此外,没有内置方法可以绑定Grid 中的行数/列数,所以我倾向于使用一些custom attached properties 来动态构建Grid 的RowDefinitions 和ColumnDefinitions一个绑定值。
因此,如果您使用 Grid,您的最终结果可能如下所示:
<ItemsControl ItemsSource="{Binding Cells}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- This is assuming you use the attached properties linked above -->
<Grid local:GridHelpers.RowCount="{Binding Height}"
local:GridHelpers.ColumnCount="{Binding Width}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- ItemContainerStyle -->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column"
Value="{Binding ColumnIndex}" />
<Setter Property="Grid.Row"
Value="{Binding RowIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Model/ViewModel 看起来像这样
public class GameViewModel
{
// These should be full properties w/ property change notification
// but leaving that out for simplicity right now
public int Height;
public int Width;
public ObservableCollection<CellModel> Cells;
}
public class CellModel
{
// Same thing, full properties w/ property change notification
public int ColumnIndex;
public int RowIndex;
public bool IsVisible;
public bool IsMine;
public int NumberAdjacentMines;
}