[ACCEPTED]-WPF: TabControl & DataTemplates-tabcontrol

Accepted answer
Score: 61

First of all, there are two templates involved 32 here:

  • TabControl.ItemTemplate, used to render the TabItem headers
  • TabControl.ContentTemplate, used to render the TabItem contents

If you don't set these properties explicitly 31 then WPF will attempt to resolve them elsewhere. It 30 will walk up the logical tree looking for 29 a resource telling it how to render your 28 view model. If it finds a DataTemplate that has a matching 27 DataType but no key, it will use it to render the 26 view model. If it doesn't find one, it'll 25 default to rendering the ToString value of the object.

So, if 24 you want to be explicit, you want something 23 like this:

<TabControl ItemsSource="{Binding Tabs}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TabTitle}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}"/>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

Since you're not being specific, WPF 22 is attempting to walk up your logical tree 21 to find an appropriate DataTemplate. When it finds it, it 20 uses it to render the view model. Where 19 it doesn't find it, it calls ToString and renders 18 that.

So to address your specific cases:

Just ItemTemplate

You've 17 explicitly stated how to render tab headers 16 but not tab contents. So the former is rendered 15 using the provided DataTemplate, but the latter will 14 default to ToString.

Just DataTemplate

You've not explicitly stated 13 how to render either tab headers or tab 12 contents. Therefore, WPF searches for an 11 appropriate DataTemplate for both. Since both contain 10 an instance of your view model (that's their 9 DataContext) then the same DataTemplate will be used to render 8 tab headers and their contents.

NOTE: you 7 didn't explicitly state that this is what's 6 happening in your question. Correct me if 5 I'm wrong.

Both

In this case, you've explicitly 4 stated how to render tab headers but not 3 tab contents. Therefore, the explicit DataTemplate is 2 used for tab headers and the implicit DataTemplate is 1 used for tab contents.

More Related questions