假设你有两种方法:
Private Sub ParentNodeMethod()
Console.WriteLine("Parent Node Method")
End Sub
Private Sub ChildNodeMethod()
Console.WriteLine("Child Node Method")
End Sub
...您有一个用于 TreeView 控件的 ContextMenuStrip,并且您想要一个特定的菜单条项 (ToolStripMenuItem) 调用 - 单击时 - 根据单击的 TreeNode 调用其中一个。
您可以利用 Action 委托并创建调用不同方法的不同操作,并将它们分配给相关 TreeNode 对象的 Tag 属性,处理 TreeView.NodeMouseClick 以显示 ContextMenuStrip 并传递正确的操作,并处理 ContextMenuStrip 的ItemClicked 事件来调用它。
将您的代码替换为:
'//
parentNode.Tag = New Action(AddressOf ParentNodeMethod)
childNode.Tag = New Action(AddressOf ChildNodeMethod)
'//
Private Sub TreeView1_NodeMouseClick(sender As Object,
e As TreeNodeMouseClickEventArgs) _
Handles TreeView1.NodeMouseClick
If e.Button = MouseButtons.Right AndAlso TypeOf e.Node.Tag Is Action Then
ContextMenuStrip1.Items(0).Tag = e.Node.Tag
ContextMenuStrip1.Show(TreeView1, e.Location)
End If
End Sub
Private Sub ContextMenuStrip1_ItemClicked(sender As Object,
e As ToolStripItemClickedEventArgs) _
Handles ContextMenuStrip1.ItemClicked
If TypeOf e.ClickedItem.Tag Is Action Then
DirectCast(e.ClickedItem.Tag, Action)()
e.ClickedItem.Tag = Nothing
End If
End Sub
另一种方法是创建Dictionary(Of TreeNode, Action),而不是将操作分配给Tag 属性:
'Class member
Private ReadOnly dict As New Dictionary(Of TreeNode, Action)
'//
dict.Add(parentNode, New Action(AddressOf ParentNodeMethod))
dict.Add(childNode, New Action(AddressOf ChildNodeMethod))
'//
Private Sub TreeView1_NodeMouseClick(sender As Object,
e As TreeNodeMouseClickEventArgs) _
Handles TreeView1.NodeMouseClick
Dim a As Action = Nothing
If e.Button = MouseButtons.Right AndAlso dict.TryGetValue(e.Node, a) Then
ContextMenuStrip1.Items(0).Tag = a
ContextMenuStrip1.Show(TreeView1, e.Location)
End If
End Sub
Private Sub ContextMenuStrip1_ItemClicked(sender As Object,
e As ToolStripItemClickedEventArgs) _
Handles ContextMenuStrip1.ItemClicked
If TypeOf e.ClickedItem.Tag Is Action Then
DirectCast(e.ClickedItem.Tag, Action)()
e.ClickedItem.Tag = Nothing
End If
End Sub
另外,正如@Jimi 已经提到的,如果相同Level 的TreeNode 对象应该调用相同的方法,则使用此属性来决定应该调用哪个方法。