Mouse Over Trigger for TreeViewItem

The problem with the IsMouseOver property on TreeViewItem in WPF is that when it is set to true for a child node it is also true for parent nodes. Therefore if you try to add a trigger with IsMouseOver property you will observe the following behavior:

Code Snippet

<TreeView x:Name="TreeViewControl" ItemsSource="{Binding}">

<TreeView.Resources>

<HierarchicalDataTemplate DataType="{x:Type local:Item}" ItemsSource="{Binding Path=SubItems}">

<TextBlock Text="{Binding Path=Name}"/>

</HierarchicalDataTemplate>

<Style TargetType="TreeViewItem">

<Style.Triggers>

<Trigger Property="IsMouseOver" Value="True">

<Setter Property="Background" Value="Pink"/>

</Trigger>

</Style.Triggers>

</Style>

</TreeView.Resources>

</TreeView>

 

MouseOverTriggerforTreeViewItem

One way to solve this is to overwrite the ControlTemplate of TreeViewItem and add a trigger with IsMouseOver propert on PART_Header. In that case trigger will be activated only if mouse is directly over the TreeViewItem, i.e. its header. Creating a ControlTemplate for TreeViewItem from scratch is not straight forward and it might require a lot of work, however you can copy the default control template of TreeViewItem from msdn. Then add MouseOver trigger among ControlTemplate.Triggers list as indicated below. With this change when you move your mouse over a TreeViewItem, parent nodes will not be affected by the trigger.

Code Snippet

<Style x:Key="{x:Type TreeViewItem}"

TargetType="{x:Type TreeViewItem}">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="{x:Type TreeViewItem}">

<ControlTemplate.Triggers>

<Trigger SourceName="PART_Header" Property="IsMouseOver" Value="True">

<Setter TargetName="Bd" Property="Background" Value="Pink"/>

</Trigger>

<Trigger Property="IsExpanded"

Value="false">

<Setter TargetName="ItemsHost"

Property="Visibility"

Value="Collapsed"/>

</Trigger>

</ControlTemplate.Triggers>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

MouseOverTriggerforTreeViewItem

Comments