Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 718
bluebit Avatar asked Aug 11 '09 15:08

bluebit


1 Answers

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> 
like image 136
Thomas Levesque Avatar answered Sep 23 '22 22:09

Thomas Levesque