views:

666

answers:

2

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!

+4  A: 

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>
Thomas Levesque
You know, WPF + MVVM has such a steep learning curve, but once you get the hang of it the solutions are actually very elegant and clean. Thanks for your help :)
bluebit
I agree that WPF has a steep learning curve, but I wouldn't say that about the MVVM pattern... actually it feels quite natural when you start using it :)
Thomas Levesque
A: 

How i can access, to set visible or hidden, or active or inactive a specific tabitem?