Dax Fohl
Dax Fohl

Reputation: 10781

How can I change the image on my TabControl's TabItem headers when the tab is selected?

I have the following TabControl in a window, and I need the images to change to "awb-white.png" and "center-weighted-white.png", respectively, when those tabs are selected. (And back to -white when they're not selected). What's the best way to go about this? Can it be done in XAML?

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TabControl>
        <TabItem>
            <TabItem.Header>
                <Image Source="images/awb-black.png" Stretch="None" />
            </TabItem.Header>
            <Grid />
        </TabItem>
        <TabItem>
            <TabItem.Header>
                <Image Source="images/center-weighted-black.png" Stretch="None" />
            </TabItem.Header>
            <Grid />
        </TabItem>
    </TabControl>
</Window>

I'm brand new to WPF so details will help a lot.

Upvotes: 2

Views: 2865

Answers (1)

brunnerh
brunnerh

Reputation: 184526

Use a Style with a default setter for the header, add a Trigger on IsSelected and created another setter for the new header.

<TabItem>
    <TabItem.Style>
         <Style TargetType="TabItem">
              <Setter Property="Header">
                  <Setter.Value>
                      <Image ...>
                  </Setter.Value>
              </Setter>
              <Style.Triggers>
                  <Trigger Property="IsSelected" Value="True">
                      <Setter Property="Header">
                          <Setter.Value>
                              <Image ...>
                          </Setter.Value>
                      </Setter>
                  </Trigger>
              </Style.Triggers>
         </Style>
    </TabItem.Style>
</TabItem>

As this is rather verbose you might want to inherit from TabItem and put that in the default template where the Image.Sources are bound to two custom properties, then you just need to set those on your instances.

Also note that the fact that the default value is in a setter is important due to precedence, if you set it directly the trigger will not override that value.

Upvotes: 3

Related Questions