【问题标题】:How can I show a context menu only when the user has clicked the root node in a TreeView?仅当用户单击 TreeView 中的根节点时,如何显示上下文菜单?
【发布时间】:2011-04-17 09:43:16
【问题描述】:

我有一个 TreeView 和一个上下文菜单。我只想在右键单击 ROOT 节点而不是子节点时显示上下文菜单。

这是我目前所拥有的。即使我右键单击子节点,这也会显示上下文菜单。如何更改此设置,以便仅在我右键单击根节点时才显示菜单?有可能吗?

if(e.Button == MouseButtons.Right)
{
    // Select the clicked node
    treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);

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

【问题讨论】:

    标签: c# .net winforms treeview contextmenu


    【解决方案1】:

    是的,这是可能的,但您需要在 if 语句中添加一些逻辑,以验证用户单击的节点是根节点。

    但是我们如何确定它是否是根节点呢?好吧,仔细考虑一下,我们可以将根节点定义为没有任何父节点的节点。所以您可以简单地检查TreeNodeParent property 并确保它是null

    将您的代码修改为如下所示:

    if (e.Button == MouseButtons.Right)
    {
        // Select the clicked node
        treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
    
        if (treeView1.SelectedNode != null && treeView.SelectedNode.Parent == null)
        {
            myContextMenuStrip.Show(treeView1, e.Location)
        }
    }
    

    您希望保留对节点本身不是null 的检查,因为您不想在他们没有单击节点时显示上下文菜单,但您需要add 检查父节点,因为这会告诉您它是否是根节点。您以编程方式指示的方式是使用逻辑 AND,即 C# 中的 && 运算符。

    【讨论】:

    • 完成了这项工作。非常感谢。
    【解决方案2】:

    检查您单击的节点是否为根节点,而不是检查它是否为null

    【讨论】:

      【解决方案3】:

      您也可以使用Level 属性:

      http://msdn.microsoft.com/EN-US/library/386b25wy(v=VS.110,d=hv.2).aspx

      If e.Button = MouseButtons.Right Then
        ' Select the clicked node
        treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y)
      
        If treeView1.SelectedNode.Level = 0 Then
          myContextMenuStrip.Show(treeView1, e.Location)
        End If
      End If
      

      【讨论】:

        猜你喜欢
        • 2022-10-17
        • 1970-01-01
        • 2018-02-12
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 1970-01-01
        相关资源
        最近更新 更多