如何仅当用户单击 TreeView 中的根节点时才显示上下文菜单?
我有一个 TreeView 和一个上下文菜单。我只想在右键单击根节点而不是子节点时显示上下文菜单。
这是我到目前为止所拥有的。即使我右键单击子节点,也会显示上下文菜单。如何更改此设置,以便仅在右键单击根节点时才显示菜单?是否可以?
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)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的,但您需要在
if
语句中添加一些逻辑,以验证用户单击的节点是否为根节点。但是我们如何知道它是否是根节点呢?好吧,仔细想想,我们可以将根节点定义为没有任何父节点的节点。因此,您只需检查
Parent<
TreeNode
的 /code> 属性并确保其为
null
。将您的代码修改为如下所示:
您希望保留节点本身不为
null
的检查,因为您不希望在它们还没有<时显示上下文菜单/em> 单击了一个节点,但您需要添加对父节点的检查,因为这会告诉您它是否是根节点。以编程方式指示的方式是使用逻辑 AND,即 C# 中的&&
运算符。Yes, it's possible, but you'll need to add some logic to your
if
statements that verifies the node the user clicked on is a root node.But how do we find out if it's a root node? Well, thinking it through, we can define a root node as one that does not have any parents. So you can simply check the
Parent
property of theTreeNode
and make sure that it isnull
.Modify your code to look something like this:
You want to retain the check that the node itself is not
null
, because you don't want to show the context menu when they haven't clicked on a node, but you need to add the check for a parent, because that tells you whether or not it's a root node. The way you indicate that programmatically is using a logical AND, which is the&&
operator in C#.检查您单击的节点是否为根节点,而不是检查它是否为
null
。Check that the node you clicked on is the root node instead of checking for it being
null
.您还可以使用
Level
属性:http://msdn.microsoft.com/EN-US/library/386b25wy(v=VS.110,d=hv.2).aspx
You can also use the
Level
property:http://msdn.microsoft.com/EN-US/library/386b25wy(v=VS.110,d=hv.2).aspx