#455 – Using ItemContainerStyle to Bind Data Elements in a Collection to a Grid

在之前的文章中,需要将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 的属性,来实现绑定。


原文地址:https://wpf.2000things.com/2011/12/21/455-using-itemcontainerstyle-to-bind-data-elements-in-a-collection-to-a-grid/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值