Kelson Ball Kelson Ball - 1 month ago 16
C# Question

WPF TabItem HeaderTemplate style applying inconsistently

I am getting some strange behavior when I follow the steps provided by other SO answers to how to style tab item headers.
With

<Style TargetType="{x:Type TabItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type TabItem}">
<buttons:MyButtonControl Content="{TemplateBinding Content}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>


And a tab control as follows

<TabControl>
<TabItem Header="Buttons">
<local:Buttons />
</TabItem>
<TabItem Header="Labels">
<local:Labels />
</TabItem>
</TabControl>


I get a tab control that looks like this

Tab control

How do I get the style to apply to all tab headers? How do I remove the default tab header style around my datatemplate?

EDIT

If I style the Template rather than the header template the content stops showing up but at least the border goes away on the header that works.

<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<buttons:MyButtonControl Content="{TemplateBinding Content}" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>


Tab Control after edit

Answer

The missing part appears to have been a ContentPresenter with the ContentSource property set to Header.

(Also using a button in the header prevents the tab from being clicked on because the button eats the click event.)

This code displays correctly.

<Style TargetType="TabItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TabItem}">
                <Border>
                    <ContentPresenter ContentSource="Header">
                        <ContentPresenter.ContentTemplate>
                            <DataTemplate>
                                <TextBlock Text="{TemplateBinding Content}" />
                            </DataTemplate>
                        </ContentPresenter.ContentTemplate>
                    </ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>