Question

I am creating a TreeView using the following method looping through an xml document.

However when any TreeViewItem is selected all the nodes in the hierarchy are getting the event triggers instead of just the selected TreeViewItem.

For example let's say we select the grandchild of a node. All the nodes including grandchild, child, parent are triggering the same event.

In other words we would expect only the grandchild trigger the associated event whereas and the event should get called only once but it ends up being called 3 times for all the nodes of the hierarchy of the selected item.

Here is the code:

TreeViewItem getTreeViewItemWithHeader(XmlNode node)
{
    TreeViewItem tvi = new TreeViewItem();
    tvi.Header = node.Name;//hdr;
    tvi.Tag = node.Attributes["Tag"].Value;
    tvi.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tvi_PreviewMouseLeftButtonDown);
    tvi.Selected += new RoutedEventHandler(tvi_Selected);

    return tvi;

}

Please let me know if you have any suggestions, thanks

N

Was it helpful?

Solution

This is working correctly. The PreviewMouseLeftButtonDown event is a routed event (in this case the strategy is tunneling). This means that the root of the visual tree gets the event first, and it works its way down until it reaches the control that originally triggered the event. The MouseLeftButtonDown and Selected events is also routed, but its strategy is bubbling - this means that the event works its way up the visual tree, starting with the control that triggered the event.

If you want a routed event to not continue to be sent, set the Handled property of the RoutedEventArgs passed in to true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top