如何获取上下文菜单所调用的TreeNode?

3

我有一个TreeView控件和一些TreeNodes。每个节点的上下文菜单基于其状态具有不同的菜单项。因此,我当前正在将每个TreeNode附加到其自己的上下文菜单。

TreeView tv = new TreeView();
TreeNode tn = New TreeNode();
tn.ContextMenu = GetContextMenu(state);
tv.Nodes.Add(tn);

然后,在 MenuItem 的点击事件中,我尝试获取 ContextMenu 所属的 TreeNode。

MenuItem mi = (MenuItem)sender;
ContextMenu tm = mi.GetContextMenu();
var sc = tm.SourceControl;

问题在于tm.SourceControl == null。我注意到TreeNode没有继承自Control,这就是为什么SourceControl属性为空的原因吗?如何获取适当的TreeNode对象?甚至是TreeView对象?

你能看一下这个StackOverFlow之前的帖子,看看它是否有帮助吗?https://dev59.com/M3VD5IYBdhLWcg3wXacd - MethodMan
那很有帮助。我在搜索中没有看到过这个。谢谢。那么,我该怎么处理这个问题? - scott
1个回答

3

我不确定是否理解您的问题。

当您在TreeView上单击时,您可以执行以下操作来获取所选节点:

void tvMouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        // Select the clicked node
        tv.SelectedNode = tv.GetNodeAt(e.X, e.Y);

        if(tv.SelectedNode != null)
        {
            myContextMenuStrip.Show(tv, e.Location)
        }
    }
}

我没有使用TreeView的点击事件,而是使用MenuItem的点击事件。但这有助于找出我的解决方案。TreeView始终可用且只有一个。因此,我直接访问它,而不是尝试从事件处理程序参数中获取它。 - scott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接