Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabItems from View collection

I am using MVVM. I have a tab control. I will have a collection of items. I want to display each of this item in the collection as a tab item. The view in each tab item is different and may have its own viewmodel. How do I achieve this? E.g. I have 3 items in the collection. The Tab item template contains an ItemControl. I would like to now have 3 Tabs created and the ItemControls inside each tabitem may be showing different views.

One way I could do is have a single view and viewmodel for each item. Now based on some condition the View will display different UI elements and behave differently. But I am afraid this will make the view quite complex over a period of time.

Edit: Goblin's solution below works fine but I have an issue when a custom style applied to TabControl.

<Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}">
<Setter Property="Template">
  <Setter.Value>
     <ControlTemplate TargetType="TabControl">
      <Grid>
         <Grid.ColumnDefinitions>
            <ColumnDefinition/> <ColumnDefinition />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
            <RowDefinition Height="Auto" Name="RowDefinition0" />
            <RowDefinition Height="*" Name="RowDefinition1" />
         </Grid.RowDefinitions>
         <TabPanel Grid.Column="0" Grid.Row="0" />
         <Border Grid.Column="0" Grid.Row="1">
             <ContentPresenter Content="{TemplateBinding TabControl.SelectedContent}" ContentTemplate="{TemplateBinding TabControl.SelectedContentTemplate}" ContentStringFormat="{TemplateBinding TabControl.SelectedContentStringFormat}" ContentSource="SelectedContent" Name="PART_SelectedContentHost" Margin="{TemplateBinding Control.Padding}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
          </Border>
          </Grid>
          <ControlTemplate.Triggers>

EDIT: This has been resolved by adding ContentTemplateSelector to the ContentPresenter in the above TabControl style

like image 908
byte Avatar asked Dec 09 '22 15:12

byte


1 Answers

Create a datatemplate for each view. Implement a DataTemplateSelector class which given an item returns the correct datatemplate. If the collection of items is called Items your xaml would look something like this

<TabControl 
    ItemsSource="{Binding Path=Items}"
    ContentTemplateSelector="{StaticResource MyTemplateSelector}" />
like image 180
Wallstreet Programmer Avatar answered Dec 25 '22 09:12

Wallstreet Programmer