tags:

views:

14

answers:

1

I would like to bind a list control (like a ListView) in a view to a collection in a view model. The collection is made up of any number of view models which also have views designed to bind to them.

While each view model in the collection will derive from a common base type, their derived types are different (as are the types of their views). For instance, one item on the list might have a view that has a text box and two buttons while another item has a check box and a combo list.

But the list control will not know its item's view types (or the number of items) at design time. How can I have the main view and/or the list control use the derived types in the main view model's collection to find the appropriate item views and bind them?

+3  A: 

You just need to provide appropriate DataTemplates in the resources for each ViewModel type :

<DataTemplate DataType="{x:Type vm:FooViewModel}">
    <v:FooView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:BarViewModel}">
    <v:BarView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:BazViewModel}">
    <v:BazView />
</DataTemplate>

Note that there is no x:Key attribute on these resources: that way, WPF picks the appropriate template automatically depending on the type of the ViewModel

Thomas Levesque
Works great - thanks!
MarkB