#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">
                    <Grid ShowGridLines="True">
                            <RowDefinition Height="*"/>
                            <!-- 7 more rows -->
                            <ColumnDefinition Width="*"/>
                            <!-- 7 more columns -->
                    <Label Content="{Binding Text}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Setter Property="Grid.Row" Value="{Binding Row}"/>
                    <Setter Property="Grid.Column" Value="{Binding Column}"/>