Khushi
Khushi

Reputation: 1051

Create a Style for TabItem in WPF

I want to show an image and Text on each and every tabItem of my TabControl.

So, I created a Style as follows:

<TabControl.Resources>
    <Style TargetType="TabItem">
        <Style.Setters>
            <Setter Property="Header">
                <Setter.Value>
                    <StackPanel Orientation="Horizontal" Background="#FF2A2A2A" Margin="-7,-2" Cursor="Hand">
                        <Image Source="{Binding Tag}" Margin="10"/>
                        <TextBlock Text="{Binding Content}" FontSize="32"  Foreground="White" Margin="0,10,10,10"/>
                    </StackPanel>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>
</TabControl.Resources>

Now in the TabItem:

<TabItem Tag="Images/Plus.png" Content="Create New" />

But I don't see any header on any tabItems??????

Upvotes: 0

Views: 350

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81348

You need to use RelativeSource to travel up Visual tree to get your property bindings to work. By default it will search for property in DataContext of Image and not on TabItem.

<Image Source="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor,
                             AncestorType=TabItem}}" Margin="10"/>

and similarly for TextBlock:

<TextBlock Text="{Binding Content, RelativeSource={RelativeSource 
                          Mode=FindAncestor, AncestorType=TabItem}}"
           FontSize="32"  Foreground="White" Margin="0,10,10,10"/>

Upvotes: 1

Valera Scherbakov
Valera Scherbakov

Reputation: 488

specify the name of the style

<TabControl.Resources>
    <Style x:Key="TabItemStyle" TargetType="{x:Type TabItem}">
        <Style.Setters>

and indicate style in TabItem

<TabItem Tag="Images/Plus.png" Content="Create New" Style="{StaticResource TabItemStyle}" />

Upvotes: 0

Related Questions