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

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

Advertisement

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: