Yellow
Yellow

Reputation: 3957

Selecting TreeViewItems by a MouseClick is called for all parent items

I have a simple TreeView class with several TreeViewItem (of my own design) in a WPF application. I want the item that is being clicked on to be selected, which is essentially very simple. However, whenever the user clicks on an element that's not the very root element, the MouseRightButtonUp event is called for all its parents, resulting in all parent nodes to be selected too. This is my code:

public class MyTreeViewItem : TreeViewItem
{
    public MyTreeViewItem()
    {
        this.MouseRightButtonDown += MyTreeViewItem_MouseRightButtonDown ;
    }

    void MyTreeViewItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (sender as MyTreeViewItem != null)
            (sender as MyTreeViewItem).IsSelected = true;
    }
}

In the debugger, I found that indeed the MyTreeViewItem_MouseRightButtonDown method is called for each parent individually. How do I avoid this?

Upvotes: 1

Views: 275

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

Routed events in WPF have a Handled property which lets you mark them as processed.

Marking the event handled will limit the visibility of the routed event to listeners along the event route. The event does still travel the remainder of the route, but only handlers specifically added with HandledEventsToo true in the AddHandler(RoutedEvent, Delegate, Boolean) method call will be invoked in response.

You can set e.Handled = true; in your code and it will not continue firing the event like that:

public class MyTreeViewItem : TreeViewItem
{
    public MyTreeViewItem()
    {
        this.MouseRightButtonDown += MyTreeViewItem_MouseRightButtonDown ;
    }

    void MyTreeViewItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {

        if (sender as MyTreeViewItem != null)
        {
            (sender as MyTreeViewItem).IsSelected = true;
            e.Handled = true;
        }
    }
}

Upvotes: 2

Related Questions