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

I showed earlier that to bind Grid.Row and Grid.Column properties on child items in an ItemsControl,  we need to set up the binding on the ContentPresenter elements that contain the individual items.  I did this by creating a class that inherited from ItemsControl and then set the bindings at runtime, programmatically.

There is a much easier way to do this, pointed out by reader Bruno (thanks Bruno)!

You can set up the bindings by specifying the ItemContainerStyle of the ItemsControl and using property setters to do the binding.

        <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>

Advertisements