Select Tree View Node on right click before displaying Context Menu in WPF

Select Tree View Node on right-click before displaying Context Menu in WPF

<TreeView ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="0,10,0,0">
<TreeView.ItemContainerStyle >
<Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
<EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="TreeViewItem_PreviewMouseRightButtonDown" />
<Setter Property="Background" Value="{Binding isSelected, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding isFocused, Mode=TwoWay}" />
</TreeView.ItemContainerStyle >
One of the possible solutions is to use e.OriginalSource and find TreeViewItem using the VisualTreeHelper:
private void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
TreeViewItem treeViewItem = GetSeleteNoteOfRight(e.OriginalSource as DependencyObject);
if (treeViewItem != null)
e.Handled = true;
static TreeViewItem GetSeleteNoteOfRight(DependencyObject dependencyObject)
while (dependencyObject != null && !(dependencyObject is TreeViewItem))
dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
return dependencyObject as TreeViewItem;

0 Comment's

Comment Form