Select TreeView Node on right click before displaying ContextMenu

alex2k8 picture alex2k8 · Feb 26, 2009 · Viewed 61.6k times · Source

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 context menu, what are the WPF alternatives?

Answer

alex2k8 picture alex2k8 · Feb 27, 2009

Depending on the way the tree was populated, the sender and the e.Source values may vary.

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 = VisualUpwardSearch(e.OriginalSource as DependencyObject);

    if (treeViewItem != null)
    {
        treeViewItem.Focus();
        e.Handled = true;
    }
}

static TreeViewItem VisualUpwardSearch(DependencyObject source)
{
    while (source != null && !(source is TreeViewItem))
        source = VisualTreeHelper.GetParent(source);

    return source as TreeViewItem;
}