secretformula
secretformula

Reputation: 6432

WPF Item Templates - TabControl

I am writing an application in which I utilize a tab control which will start with one tab open but allows the user to open multiple other tabs.

Each tab that is openned should have a treeview inside which I fill using databinding when the user loads a file.

I am new to WPF but I feel as if there is a way in which I can create a template containing each of the elements the TabItems should contain. How can I do this using templates? Right now my WPF for the tab items is the following

<TabItem Header="Survey 1">
        <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
                  Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" />
 </TabItem>

Upvotes: 1

Views: 4362

Answers (2)

Rachel
Rachel

Reputation: 132648

Usually in this sort of situation I bind my TabControl.ItemsSource to a ObservableCollect<ViewModelBase> OpenTabs, so my ViewModel is in charge of adding/removing new tabs as needed.

Then if you want something in every Tab, then overwrite the TabControl.ItemTemplate and use the following line to specify where to display the currently selected TabItem

<ContentControl Content="{Binding }" />

If you don't need to setup something in every single tab, you don't need to overwrite the TabControl.ItemTemplate - it will default to displaying the currently selected ViewModelBase in the Tab.

And I use DataTemplates to specify which View to use

<DataTemplate TargetType="{x:Type local:TabAViewModel}">
    <local:TabAView />
</DataTemplate>

<DataTemplate TargetType="{x:Type local:TabBViewModel}">
    <local:TabBView />
</DataTemplate>

<DataTemplate TargetType="{x:Type local:TabCViewModel}">
    <local:TabCView />
</DataTemplate>

Upvotes: 2

David Masters
David Masters

Reputation: 8295

I think you want something like this:

<Window x:Class="TestWpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Window.Resources>
    <DataTemplate x:Key="TabItemTemplate">
        <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
                    Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" />
    </DataTemplate>

</Window.Resources>
<Grid>
    <TabControl ItemsSource="{Binding ListThatPowersTheTabs}"
                ItemTemplate="{StaticResource TabItemTemplate}">
    </TabControl>
</Grid>

You basically create re-usable templates as static resources which you refer to by their key name.

Upvotes: 3

Related Questions