在之前的文章中,需要将ItemsControl的子元素的行列和Grid.Row 和Grid.Column 属性绑定,我们的做法是将行列绑定到包含显示项的ContentPresenter 的Grid.Row 和Grid.Column ,是通过继承ItemsControl 类然后重写PrepareContainerForItemOverride 实现。
但是有一个更简单的方法(有原文的读者Bruno 指出)。
你可以通过指定ItemsControl 的ItemContainerStyle 建立绑定。
<ItemsControl ItemsSource="{Binding ChessPieces}" Height="500" Width="500">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<!-- 7 more rows -->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<!-- 7 more columns -->
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Text}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding Row}"/>
<Setter Property="Grid.Column" Value="{Binding Column}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
上面的代码中通过设置ItemContainerStyle 设置ContentPresenter 的属性,来实现绑定。