1
votes

I know this question has been asked and answered several times already but I still don't get it. I seem to be missing a piece of understanding.

I have a TabControl bound to an observable list of viewmodels. The viewmodels can be of different types, derived from the same base type, of course. When a viewmodel is added to the list I want the tabcontrol adds a new tabpage based on the type of the view model.

I do not understand how to set up the ContentTemplate of the TabControl to pick the right view based on the type of the view model.

A Basic example can be found here, but I do not get it up and running with dynamic views:

How to bind items of a TabControl to an observable collection in wpf?

Thanks! Johannes

1

1 Answers

5
votes

Ok, i will modify the sample code in the answer you linked:

<Window.Resources>
    <DataTemplate x:Key="templateForTheHeader" DataType="{x:Type vm:BaseViewModel}">
        <TextBlock Text="{Binding CommonPropertyToDisplayInTheHeader}"/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:ViewModel1}">
        <TextBlock Text="{Binding PropertyInVM1}"/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:ViewModel2}">
        <TextBlock Text="{Binding PropertyInVM2}"/>
    </DataTemplate>
</Window.Resources>

...

<TabControl ItemsSource="{Binding YourCollection}"
            ItemTemplate="{StaticResource templateForTheHeader}">
</TabControl>

The header displays some property in the base VM class. And the important thing, i removed the x:key of the other DataTemplates, this will make it being applied to every instance of the defined DataType found in the Window (ContentTemplate in the TabControl not needed).

YourCollection is a mix of objects, each of it will get its template applied based on its type if a DataTemplate with matching DataType exists. Simple uh?