Search code examples
c#.netwpftreeviewitem

.NET TreeViewItem Selected only when itself is selected, not its child?


Currently, I have a tree view that looks like this:

+Country
  +StateA
    -CityA
    -CityB
  +StateB
    -CityC
  +State
    -CityD

Where the Cities are the end leaves of the tree and are selectable and have their own Selected handler. The Country is also selectable and has its own Selected handler.

The handlers are assigned as so:

countryTreeItem.Selected += countrySelectedHandler;
...
cityTreeItem.Selected += citySelectedHandler;

When I select a City, the parent State and the parent Country are also selected. This means that both citySelectedHandler and countrySelectedHandler are selected when I select a leaf (Say, City A)

Is there a way to make sure that only the leaf item gets selected? If I click on CityA I only want citySelectedHandler for that City to run, instead of countrySelectedHandler of its ancestor to run also.

However, I still want countrySelectedHandler to run when the Country is selected (clicked on). Simply removing the handler for the ancestor won't do.

Thank you!


Solution

  • To stop propagation of the event, you can set e.Handled = true. This way the event will not bubble up to the ancestor tree items.