views:

933

answers:

2

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.

+3  A: 

Use an ItemsControl, and set its ItemsPanel to a WrapPanel:

<ItemsControl ItemsSource="{Binding Something}" ItemTemplate="{StaticResource YourDataTemplate}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>
itowlson
+3  A: 

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>
Andrew Shepherd
Thanks for the insight Andrew. I've done this, and have encountered another problem. I'm hoping you can help with this one too, otherwise I'll start another question. I threw <v:ServiceMonitorView />, my UserControl, in the DataTemplate. I'm getting the following error: Could not create an instance of type 'ServiceMonitorView'. The user control has zero code outside of the default, generated constructor...so there should not be any constructor code throwing an exception.
jrista
@jrista: I would say that that's a separate problem which belongs in an independent question. (I don't know the answer, but I'm interested in what it would be)
Andrew Shepherd