[英]How can I show a context menu only when the user has clicked the root node in a TreeView?
我有一個TreeView和一個上下文菜單。 我只想在右鍵單擊ROOT節點而不是子節點時顯示Context Menu。
到目前為止,這就是我所擁有的。 即使我右鍵單擊子節點,這也會顯示上下文菜單。 如何更改此設置,以便僅在右鍵單擊根節點時才顯示菜單? 可能嗎?
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)
}
}
是的,這是可能的,但是您需要在if
語句中添加一些邏輯,以驗證用戶單擊的節點是根節點。
但是,我們如何確定它是否是根節點呢? 好了,仔細考慮一下,我們可以將根節點定義為沒有任何父節點的根節點。 因此,您可以簡單地檢查TreeNode
的Parent
屬性 ,並確保它為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
的檢查,因為您不想在未單擊節點時顯示上下文菜單,但是您需要為父節點添加檢查,因為這告訴您它是否是根節點。 您以編程方式表明使用邏輯AND的方式,這是C#中的&&
運算符。
您還可以使用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
檢查您單擊的節點是否是根節點,而不是檢查它是否為null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.