I would like to select a WPF TreeView Node on right click, right before the ContextMenu displayed.
For WinForms I could use code like this Find node clicked under co
If you want a XAML-only solution you can use Blend Interactivity.
Assume the TreeView
is data bound to a hierarchical collection of view-models having a Boolean
property IsSelected
and a String
property Name
as well as a collection of child items named Children
.
There are two interesting parts:
The TreeViewItem.IsSelected
property is bound to the IsSelected
property on the view-model. Setting the IsSelected
property on the view-model to true will select the corresponding node in the tree.
When PreviewMouseRightButtonDown
fires on the visual part of the node (in this sample a TextBlock
) the IsSelected
property on the view-model is set to true. Going back to 1. you can see that the corresponding node that was clicked on in the tree becomes the selected node.
One way to get Blend Interactivity in your project is to use the NuGet package Unofficial.Blend.Interactivity.