#448 – Data Binding Elements in a Collection to a Grid, part I

Assume that you have a collection of objects that you want to place in a grid, with their position only known at runtime.  You might have properties on the objects indicating what row and column they should be placed in and then use data binding to locate the objects.

You can use a Grid panel as the ItemsPanel of an ItemsControl.  This dictates the layout of the items in the collection.  You can then specify the ItemTemplate to indicate how each item should be displayed.

Your first try might look something like this:

    <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}" Grid.Row="{Binding Row}" Grid.Column="{Binding Column}"
                        HorizontalAlignment="Center" VerticalAlignment="Center"/>

Next time–create a collection of ChessPiece objects at runtime.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #448 – Data Binding Elements in a Collection to a Grid, part I

  1. Pingback: Dew Drop – December 12, 2011 | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: