6

I would like to arrange items of a collection in a grid with a specific number of columns and rows (say 4x6). Each item exposes the dependency properties (integer) X and Y and should be placed in the relevant cell of the grid. Note that the collection can change during runtime which should update the grid items.

I couldn't find any good solution. But maybe it is even possible without using the code-behind?

Don't mind conversion or something. This stuff changes anyway. The used collection class isn't important. (You can choose one.)

How can I solve this problem? Any appropriate suggestions would we welcome, thanks.

H.B.
  • 166,899
  • 29
  • 327
  • 400

1 Answers1

6
<ItemsControl ItemsSource="{Binding YourItems}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Grid.Column" Value="{Binding X}"/>
            <Setter Property="Grid.Row" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 2
    Good solution, although you need to put Grid.RowDefinitions and Grid.ColumnDefinitions in there with the max of X and Y as RowDefinition and ColumnDefinition, respectively.... otherwise they will simply overlap each-other. – Goblin Sep 26 '10 at 17:19
  • It's worth mentioning that you have to use `ItemContainerStyle` to do this. You can't just set `Grid.Row` and `Grid.Column` in the `ItemTemplate` because whatever element is generated by the `ItemTemplate` is wrapped in the container that the `ItemsControl` generates, and the `Grid.Row` and `Grid.Column` have to be set on that container in order for the `Grid` to see them. – Robert Rossney Sep 26 '10 at 19:05
  • Works fine, thank you. @Robert: Thanks for the explanation. I didn't even know, that Grids generate containers... –  Sep 27 '10 at 13:25