在显示ContextMenu之前,右键单击选择TreeView节点 [英] Select TreeView Node on right click before displaying ContextMenu

查看:109
本文介绍了在显示ContextMenu之前,右键单击选择TreeView节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想右键单击WPF TreeView节点,即在显示ContextMenu之前。

I would like to select a WPF TreeView Node on right click, right before the ContextMenu displayed.

对于WinForms,我可以使用这样的代码在上下文菜单下找到单击的节点,WPF替代品是什么?

For WinForms I could use code like this Find node clicked under context menu, what are the WPF alternatives?

推荐答案

取决于树的填充方式,发送方和e.Source的值可能会发生变化

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

可能的解决方案之一是使用e.OriginalSource并找到TreeViewItem使用VisualTreeHelper:

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;
}

这篇关于在显示ContextMenu之前,右键单击选择TreeView节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆