1

I have a usercontrol that creates more of itself, overlapping inside it as needed (its a sort of tree view). I wanted to add a highlight effect so I attached it to mouseenter/mouseleave events but as soon as I move the mouse over one of the child instances of the UC, the parent also receives the event and lights up.

I tried setting the e.handled = true assuming the event was passed down through the tree from child to parent but this is not the case, each instance of the nested controls generates their own event.

One way I could prevent this is when a control receives this event, it would scan through all of its children and grandchildren(etc) to see if any of those is also highlighted to prevent itself from doing that but I'm not sure the overlapping controls recieve the event in any particular order and this shouldn't be that difficult.

How can I prevent the event from triggering unless the control is the topmost visible one?

user81993
  • 6,167
  • 6
  • 32
  • 64

1 Answers1

0

Very typical problem with tree view. A parent is also getting highlighted cause actually you are also over that TreeViewItem(from visual tree design perspective).

Please see this link to know how to do it using tamplate and triggers.

else we can also be smart and a very smart shortcut would be

 private void TreeView_MouseEnter(object sender, MouseEventArgs e)
    {
        var treeItem = (e.OriginalSource as TreeViewItem);
        foreach (var child in treeItem.Items)
        {
            if ((child as TreeViewItem).IsMouseOver)
                return;
        }
        treeItem.Background = new SolidColorBrush(Colors.Red);

    }

if event setter is

 <Style TargetType="{x:Type TreeViewItem}">
        <EventSetter Event="MouseEnter" Handler="TreeView_MouseEnter" />                    
 </Style>

Cause the event will always trigger for child first so Nullifying the parent mouse enter events. :)

Also programmaticly we can always figure out the right TreeViewItem where you can check the highlight of child item in a recursive function. write same logic at mouse exit logic.

hopefully this will do.

Community
  • 1
  • 1
Kylo Ren
  • 8,551
  • 6
  • 41
  • 66