Linking TabItem Content Controls

I have a TabControl with ItemsSource set to ObservableCollection<BookTab> and using ContentTemplateSelector to create different tabs.

 class BookTab { public string Name { get; set; } public string Type { get; set; } public object Data { get; set; } } <TabControl Name="tabControl" ContentTemplateSelector="{StaticResource tabTemplateSelector}"> <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="Header" Value="{Binding Name}"/> <Setter Property="Content" Value="{Binding}"/> </Style> </TabControl.ItemContainerStyle> </TabControl> 

The type in BookTab defines the DataTemplate used on the corresponding tab, the Name is displayed in the header of the tab, and the data should be displayed in the contents of the tabs, that is, in the DataGrid. Data is set to ObservableCollections for different types.

A DataTemplate might look like this:

 <DataTemplate x:Key="bookTabTemplate"> <TabItem Name="bookTab"> <Grid> <DataGrid Name="bookGrid"> ... </DataGrid> </Grid> </TabItem> </DataTemplate> 

I tried different ways to bind the Data property to a DataGrid ItemsSource, but all I got is a grid displaying the word "Book" (the value of the BookTab Name property). I assume that I need to somehow extend the TabControl binding to the DataGrid, but I cannot figure it out.

0
source share
2 answers

I would do it like this:

 <TabControl SelectedItem="{Binding CurrentBook}" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding BookList}"> <TabControl.ContentTemplate> <DataTemplate> <Grid> <ContentControl Content="{Binding Data}" </Grid> </DataTemplate> </TabControl.ContentTemplate> <TabControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </TabControl.ItemTemplate> </TabControl> 

... and later you define in your app.xaml how the contents of your data will be displayed ...

  <DataTemplate DataType="{x:Type viewmodel:bookviewmodel1}"> <view:bookview1/> </DataTemplate> 

All you have to do is create a view (usercontrol) for each type.

NTN

+1
source

your datagrid data context is probably BookTab (you can confirm this with snoop )

If this is correct, all you have to do is bind the datagrid data source to the BookTab Data property p>

 <DataGrid Name="bookGrid" ItemsSource="{Binding Path=Data}" /> 

That should do the trick

0
source

All Articles