创建行和单元格的两级视图模型。将行绑定到 ItemsControl,然后在项目模板中,将单元格绑定到另一个 ItemsControl。每个单元格都有一个属性来判断它是偶数还是奇数,因此您可以实现棋盘格模式。您可以通过单元格的附加属性公开游戏状态,以通过数据绑定显示棋盘位置。
最后,由于单元格的大小是固定的,所以将整个单元格包裹在 Viewbox 中以适合您的容器。
视图模型:
public class BoardViewModel
{
private readonly int _rows;
private readonly int _columns;
public BoardViewModel(int rows, int columns)
{
_rows = rows;
_columns = columns;
}
public IEnumerable<RowViewModel> Rows
{
get
{
return Enumerable
.Range(0, _rows)
.Select(row => new RowViewModel(row, _columns))
.ToList();
}
}
}
public class RowViewModel
{
private readonly int _row;
private readonly int _columns;
public RowViewModel(int row, int columns)
{
_row = row;
_columns = columns;
}
public IEnumerable<CellViewModel> Cells
{
get
{
return Enumerable
.Range(0, _columns)
.Select(column => new CellViewModel(_row, column))
.ToList();
}
}
}
public class CellViewModel
{
private readonly int _row;
private readonly int _column;
public CellViewModel(int row, int column)
{
_row = row;
_column = column;
}
public bool IsEven
{
get { return (_row + _column) % 2 == 0; }
}
}
值转换器:
public class CellColorValueConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return Application.Current.Resources[
(bool)value == true
? "EvenCellColor"
: "OddCellColor"];
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<Window.Resources>
<local:CellColorValueConverter
x:Key="CellColor" />
</Window.Resources>
<Grid>
<Viewbox>
<ItemsControl
ItemsSource="{Binding Rows}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl
ItemsSource="{Binding Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel
Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle
Width="50"
Height="50"
Fill="{Binding IsEven, Converter={StaticResource CellColor}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Viewbox>
</Grid>