Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you bind a grid's children to a list?

Tags:

mvvm

wpf

bind

grid

In my ViewModel I have a list of items that I would like a grid in my view to bind to (the items will be the grids children). The list is a list of view models for the items.

How do you bind a grid to the list (I can access .children in code but not xaml)? Also, how do you specify the data template (another xaml file) for the view models in the list so that they are rendered correctly within the grid.

Thanks

like image 276
Dan dot net Avatar asked Sep 08 '09 18:09

Dan dot net


1 Answers

Use an ItemsControl with the ItemsPanel set to a Grid :

<ItemsControl ItemsSource="{Binding TheList}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Grid/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>

In the ItemsControl's ItemContainerStyle, you might want to bind the Grid.Row and Grid.Column attached properties to some property of the items :

  <ItemsControl.ItemContainerStyle>
    <Style TargetType="{x:Type FrameworkElement}">
        <Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
        <Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
    </Style>
  </ItemsControl.ItemContainerStyle>
like image 115
Thomas Levesque Avatar answered Oct 21 '22 12:10

Thomas Levesque