Frage

I have some TabItems, each one containg one image and a textblock. Here is the code:

<TabItem.Header>
<ContentControl>
    <ContentControl.Template>
        <ControlTemplate>
            <StackPanel x:Name="sp" Orientation="Horizontal">
                <Image x:Name="img" Source="img0.png"/>
                <TextBlock x:Name="tb" Text="Tab1" VerticalAlignment="Center" Foreground="Green"/>
            </StackPanel>
            <ControlTemplate.Triggers>
                <Trigger Property="TabItem.IsSelected" Value="True">
                    <Setter TargetName="img" Property="Source" Value="img1.png" />
                    <Setter TargetName="tb" Property="Foreground" Value="Red" />
                    <Setter Property="FontWeight" Value="Bold"/>
                </Trigger>
                <Trigger SourceName="sp" Property="IsMouseOver" Value="True">
                    <Setter TargetName="img" Property="Source" Value="img1.png" />
                    <Setter TargetName="tb" Property="Foreground" Value="Red" />
                    <Setter Property="FontWeight" Value="Bold"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

What I'm trying to achieve is to change the image's source and textblock's foreground value when the TabItem is selected. The IsMouseOver behaviour is working properly but the TabItem.IsSelected is not working as expected. Basically this code is not doing what I'm thinking it should do:

<Trigger Property="TabItem.IsSelected" Value="True">
<Setter TargetName="img" Property="Source" Value="img1.png" />
<Setter TargetName="tb" Property="Foreground" Value="Red" />
<Setter Property="FontWeight" Value="Bold"/>

Please share your opinion.

Thank you.

War es hilfreich?

Lösung

You are trying to reach the IsSelected property of the TabItem from the TabItem.Header and that can't be accomplished with an ordinary Trigger. Instead, you need to use a DataTrigger so that you can Bind to the IsSelected property with a RelativeSource Binding:

<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=
    {x:Type TabItem}}}" Value="True">
    <Setter TargetName="img" Property="Source" 
        Value="/WpfApplication1;component/Images/Tulips.jpg" />
    <Setter TargetName="tb" Property="Foreground" Value="Red" />
    <Setter Property="TextElement.FontWeight" Value="Bold"/>
</DataTrigger> 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top