简体   繁体   中英

Hierarchical data template trigger selected item property

I have created a static application resource for my TreeView style. I have a custom type as the hierarchical data template type, let's call it Foobar. The HierarchicalDataTemplate items source is bound to the Foobar's FooCollection.

The custom object binding is not an issue. Problem is I want to change style of the selected TreeViewItem using triggers. The trigger for property IsMouseOver trigger as it should. But I cannot find anywhere to trigger the property IsSelected in my HierarchicalDataTemplate.Triggers ?

<Style TargetType="TreeView" x:Key="TreeView">
    <Setter Property="BorderBrush" Value="{x:Null}"/>
    <Setter Property="Background" Value="#00000000"/>

    <Style.Resources>

        <!--Foobar tree view items-->
        <HierarchicalDataTemplate DataType="{x:Type f:Foobar}" ItemsSource="{Binding FooCollection}">

            <TextBlock Name="tbbName" Text="{Binding Name}" Foreground="#7FFFFFFF" FontSize="16"/>

            <HierarchicalDataTemplate.Triggers>

                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="tbbName" Property="Effect">
                        <Setter.Value>
                            <DropShadowEffect ShadowDepth="0" Color="#7FFFFFFF" Opacity="1" BlurRadius="20"/>
                        </Setter.Value>
                    </Setter>
                    <Setter TargetName="tbbName" Property="Foreground" Value="#AFFFFFFF"/>
                </Trigger>

            </HierarchicalDataTemplate.Triggers>
        </HierarchicalDataTemplate>
    </Style.Resources>
</Style>

What you can do is binding the IsSelected -property from TreeViewItem to a corresponding property in Foobar

class Foobar : INotifyPropertyChanged
{
    ...
    private bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            if(_isSelected == value)
                return;
            _isSelected = value;
            OnPropertyChanged();
        }
    }
    ...
}
<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
            ...
        </Style>
    </TreeView.ItemContainerStyle>
    ...
</TreeView>

then you can use a DataTrigger

<DataTrigger Binding="{Binding IsSelected}" Value="True">
    <DataTrigger.Setters>
        ...
    </DataTrigger.Setters>
</DataTrigger>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM