您需要在后端使用某种 ViewModel,然后利用 DataBinding。
假设以下(人为的)ViewModel 结构表示一个四连接板。
BoardViewModel.cs
public class BoardViewModel
{
public BoardViewModel()
{
var rand = new Random();
Squares = Enumerable
.Range(1, 42)
.Select(a => new SquareViewModel() { Token = rand.Next(-1, 2) })
.ToList();
}
public List<SquareViewModel> Squares { get; set; }
}
SquareViewModel.cs
public class SquareViewModel : INotifyPropertyChanged
{
private int _Token;
public int Token
{
get
{
return _Token;
}
set
{
if (_Token.Equals(value)) return;
_Token = value;
RaisePropertyChanged("Token");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
var handlers = PropertyChanged;
if (handlers != null)
{
var args = new PropertyChangedEventArgs(property);
handlers(this, args);
}
}
}
然后您可以使用以下 XAML 来表示您的板。
主窗口.xaml
<Window
x:Class="ConnectFour.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:ConnectFour="clr-namespace:ConnectFour"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignInstance Type={x:Type ConnectFour:BoardViewModel}, IsDesignTimeCreatable=True}">
<ItemsControl
ItemsSource="{Binding Squares}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse
Stroke="Magenta">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Style.Triggers>
<DataTrigger Binding="{Binding Token}" Value="0">
<Setter Property="Fill" Value="Black" />
</DataTrigger>
<DataTrigger Binding="{Binding Token}" Value="1">
<Setter Property="Fill" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" Columns="6" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Window>
需要注意的重要事项是:
- 基于 Square 的 Token 属性值设置椭圆颜色的 DataTrigger。
- 使用带有 UniformGrid 支持的 ItemsPanel。
- SquareViewModel 中 INotifyPropertyChanged 的实现,这样当 Token 的值发生变化时,View 就代表了这一点。
- d:DataContext 属性的使用,它将表单的设计时 DataContext 设置为 BoardViewModel 的实例(将自身初始化为随机标记)。
在运行时,您需要将板视图的 DataContext 设置为 BoardViewModel 的真实实例(或任何您的 ViewModel 被调用),但如何更改标记颜色的基本概念已经存在。