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

bluebit picture bluebit · Aug 11, 2009 · Viewed 14.2k times · Source

What is the simplest example of binding the items of a TabControl to an ObservableCollection?

Each tab's content will have unique data, and indeed this data will have observableCollections of its own bound to the items components.

Currently I have a user control, which I would like to set as the content of each tab as soon as it is created. I also need to dynamically set the datacontext of this new user control when the tab is created. So, essentially, I would like the tabcontrol's observablecollection contain modelviews that map to the data in each tab.

On top of that, I need to do all this without violating MVVM in WPF! Any help?

Much appreciated!

Answer

Thomas Levesque picture Thomas Levesque · Aug 11, 2009

Basic example :

<Window.Resources>

    <DataTemplate x:Key="templateForTheContent" DataType="{x:Type vm:TheViewModelType}">
        <v:YourUserControl/>
    </DataTemplate>

    <DataTemplate x:Key="templateForTheHeader" DataType="{x:Type vm:TheViewModelType}">
        <TextBlock Text="{Binding ThePropertyToDisplayInTheHeader}"/>
    </DataTemplate>

</Window.Resources>

...

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