Binding ObservableCollection items to UserControl in WrapPanel?

jrista picture jrista · Oct 16, 2009 · Viewed 11.8k times · Source

I may just be missing something obvious here, so I apologize if this is a really dumb question. I have a WrapPanel in a view that I need to bind to an ObservableCollection on the ViewModel. This ObservableCollection contains a different type of ViewModel that needs to be bound to another type of view when displayed in the WrapPanel. The goal is to create a wrappable list of items, each of which displays via an instance of a smaller view which should be added to the WrapPanel.

I am using MVVM, and the ViewModel does not have direct access to the View. I would rather not create a binding between the ViewModel and the View if at all possible, so manually adding items to the WrapPanel.Children collection is not a viable option. I am at a loss as to how I can bind a collection of child ViewModel objects to the WrapPanel in such a way that it will create instances of another view and add them to itself. Am I simply approaching the problem incorrectly? I figure there is probably a DataTemplate involved, but it doesn't appear that a WrapPanel has a DataTemplate, nor is it bindable.

Thanks for any insight.

Answer

Andrew Shepherd picture Andrew Shepherd · Oct 16, 2009

What you need is a ListView that uses a WrapPanel to host all of the items.

<ListView ItemsSource={...}>
   <ListView.ItemsPanel>
     <ItemsPanelTemplate>
       <WrapPanel IsItemsHost="True" />
     </ItemsPanelTemplate>
   </ListView.ItemsPanel>
   <ListView.ItemTemplate>
      <DataTemplate>
        <!-- Fill in how you want each item to look here -->
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>