WPF: Right click and select on a TreeView


The default behavior of a right click on a TreeView in WPF is that it shows the context menu if one is set but it does not select the item that the mouse is over. You can use this snippet to have it select the item the mouse is over before showing the context menu (just be sure to have appropriate null checks in place). To be clear, the OnPreviewMouseRightButtonDown event goes on the TreeView object in your XAML.

This has been updated with nullable annotations in mind.

/// <summary>
/// Sets the selection of an item with the right click button before showing
/// the context menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuTreeView_OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    var treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject);

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

/// <summary>
/// Searches for the <see cref="TreeViewItem"/> up the parent tree.
/// </summary>
/// <param name="source"></param>
public static TreeViewItem? VisualUpwardSearch(DependencyObject? source)
{
    while (source != null && source is not TreeViewItem)
    {
        source = VisualTreeHelper.GetParent(source);
    }

    return source as TreeViewItem;
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.