How to change the color of the selected tab in the TabControl?

aromore picture aromore · Aug 27, 2013 · Viewed 11.5k times · Source

I am implementing a TabControl for a dialog box in WPF. The color of the selected tab (mouse-down) is white by default. I want to change the color of that selected tab to the color of hover (when I hover over a tab, the color of the tab changes to an Office-blue-gradient, which is what I want the color of the selected tab to be on mouse-click).

How can I do that?

This piece of code does not work:

<Style x:Key="StyleTabControl" TargetType="{x:Type TabItem}">
    <Setter Property="Background" Value="#FFFDFDFD"/>
    <Style.Triggers>
        <Trigger Property="IsSelected "  Value="True">
            <Setter Property="Background" Value="SlateGray"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>

Note: I also tried IsMouseCaptured event for the trigger property. Still does not work.

Answer

aromore picture aromore · Aug 27, 2013

Alright...after hours of trying, I have realized that the TabItem selection behaviour is defined at the Template level. So, if I wana change the backgrnd color, I do this:

<Window.Resources>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <Border>
                            <Grid>
                                <Grid>
                                    <Border x:Name="border" 
                                            CornerRadius="3,3,0,0"
                                            Background="WhiteSmoke"/>
                                </Grid>
                                    <ContentPresenter ContentSource="Header"
                                                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver"
                                     Value="True">
                                <Setter TargetName="border"
                                        Property="Background"
                                        Value="LightGray" />
                            </Trigger>
                            <Trigger Property="IsSelected"
                                     Value="True">
                                <Setter TargetName="border"
                                        Property="Background"
                                        Value="LightGray" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>