views:

41

answers:

2

Fairly new to WPF...

I have a collection of data I would like to bind to a grid panel. Each object contains its grid row and column, as well as stuff to fill in at the grid location. I really like how I can create data templates in the listbox XAML to create a UI with almost nothing in the code behind for it. Is there a way to create a data template for grid panel elements, and bind the panel to a data collection?

+1  A: 

You can use an ItemsControl with a Grid as its panel. Here is an example. XAML:

    <ItemsControl x:Name="myItems">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding MyText}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Style.Setters>
                    <Setter Property="Grid.Row" Value="{Binding MyRow}" />
                    <Setter Property="Grid.Column" Value="{Binding MyColumn}" />
                </Style.Setters>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>

Codebehind (for testing purposes):

    public Window1()
    {
        InitializeComponent();
        myItems.ItemsSource = new[] {
            new {MyRow = 0, MyColumn = 0, MyText="top left"},
            new {MyRow = 1, MyColumn = 1, MyText="middle"},
            new {MyRow = 2, MyColumn = 2, MyText="bottom right"}
        };
    }
Heinzi
A: 

Not sure if this will help you, but why don't you try setting the ItemsPanel of an ItemsControl (ListBox, ListView) to a UniformGrid. Something like this:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

It's similar to the previous solution, only a little more dynamic.

Carlo