0

How can I change the background color of TreeViewItem when it is hovered over?

After reading a few articles/questions, including this one WPF TreeView Highlight Row On Hover, I thought the appropriate action to take was to create a style template for my TreeView as such:

<Style x:Key="TreeViewItemStyle1" TargetType="{x:Type TreeViewItem}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Green" />
        </Trigger>
    </Style.Triggers>
</Style>

Then assign it to my TreeView:

    <TreeView ItemsSource="{Binding Folders}"
              ItemContainerStyle="{DynamicResource TreeViewItemStyle1}"/>

But that doesn't appear to work. It does change the color as I hover over it but it leaves highlighted making my TreeView look totally messed up:

Messed up TreeView

I've tried resetting the color when IsMouseOver is false:

<Trigger Property="IsMouseOver" Value="False">
    <Setter Property="Background" Value="White" />
</Trigger>

But it still leaves multiple nodes highlighted and only resets them when I move over them one at the time.

Any ideas?

Thanks.

Thierry
  • 6,142
  • 13
  • 66
  • 117
  • *"look totally messed up"* - do you know what if you highlight a `TreeView` child it will highlight all parents? – Sinatr Jun 19 '17 at 15:18
  • Sorry but I'm not sure I understand. Are you asking a question or making a statement? if you're asking me if all parents nodes are getting highlighted if I hover over a child, the answer is no. Only the nodes I hover over get highlighted and remain in that state, thus the term "messed up". If you're saying that this is the default behaviour for a treeview, that is not correct. Remove the triggers in above sample and hovering works as expected. Looking at various other apps such as MS Explorer, SQL Server Mgt Studio, VS just to name a few, do not highlight the parent nodes on child selection. – Thierry Jun 20 '17 at 08:49
  • Disregards my previous comments. I see what you mean now, trying your style. – Sinatr Jun 20 '17 at 08:59
  • Possible duplicate of [How can I make WPF Trigger for IsMouseOver on TreeViewItem NOT affect all parents of the moused-over control?](https://stackoverflow.com/questions/1131161/how-can-i-make-wpf-trigger-for-ismouseover-on-treeviewitem-not-affect-all-parent) – Sinatr Jun 20 '17 at 09:38
  • @Sinatr Thanks for posting this link. This is obviously a WPF Treeview behaviour. I'll look into it some more later and see if there is another way to go about by using VisualState instead. – Thierry Jun 20 '17 at 10:16

0 Answers0