How to display context menu for tree view item in wpf using the hierarchical data template? How to display context menu only for CountryTemplate:
One of the reasons why context menus do not work as cleanly as they could is because by default, they are in a different visual tree to everything else, so the DataContext cannot be found.
The key insight is to create a
that defines a context menu, then attach that style to a target element, which hooks up the context menu. This shifts the context menu into a visual tree that is lined up with the defaultDataContextyou want.
First, create the style:
Then, hook the context menu up anywhere you want, without running into issues caused by different visual trees.
Example 1:
Example 2: