Search code examples
wpfdatatemplatetabcontroltabitem

TabItem - how to access element in custom HeaderTemplate from TabItem Style Trigger


I have following code:

<Window x:Class="kkk.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

        <Style TargetType="{x:Type TabItem}" x:Key="maintemplate">

            <Style.Resources>
                <DataTemplate x:Key="headertemplate" DataType="{x:Type TabItem}">
                    <StackPanel Orientation="Horizontal">
                        <ContentPresenter Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem} }, Path=Header}"/>
                        <Button Content="X" x:Name="CloseButton">
                            <Button.LayoutTransform>
                                <ScaleTransform ScaleX="0.8" ScaleY="0.5"></ScaleTransform>
                            </Button.LayoutTransform>
                        </Button>
                    </StackPanel>
                </DataTemplate>
            </Style.Resources>

            <Setter Property="HeaderTemplate" Value="{StaticResource headertemplate}"></Setter>

        </Style>

    </Window.Resources>
    <Grid>

        <TabControl>
            <TabItem Header="tab1" Style="{StaticResource maintemplate}"></TabItem>
            <TabItem Header="tab1" Style="{StaticResource maintemplate}"></TabItem>
        </TabControl>

    </Grid>
</Window>

It creates tabcontrol with small x button on each tabitem header (it will be used to close tab). Now I want to hide this button when tab is not selected. I tried somwthing like:

<Style.Triggers>
                <Trigger Property="IsSelected" Value="False">
                    <Setter Property="????" Value="Visible"></Setter>
                </Trigger>
            </Style.Triggers>

But I dont know how to access CloseButton from TabItem Style Trigger -> I tried TargetName="CloseButton" but it doesnt work...


Solution

  • I would set the style trigger on your Button instead of on the TabItem, and use a RelativeSource binding to get the TabItem.IsSelected value

    <Style x:Key="CloseButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Visibility" Value="Visible"></Setter>
        <Style.Triggers>
            <DataTrigger Property="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}" Value="True">
                <Setter Property="Visibility" Value="Visible"></Setter>
            </DataTrigger >
        </Style.Triggers>
    </Style>