下面的示例演示了如何创建一个自定义菜单,并在 节点指示器单元格 被单击时显示此菜单。 此菜单包含“Delete Node”命令,允许最终用户删除节点。 结果显示如下:
为了显示自定义菜单,接管了 MouseDown 事件。 当此事件发生时,TreeList.CalcHitInfo 方法被调用,以便于识别被单击的 TreeList 元素。 在单击节点指示器单元格的情况下,自定义菜单被创建并显示。
最终用户可以选择“Delete Node”菜单命令,或者按下 ESC 键关闭菜单。 如果选择了“Delete Node”命令,则指派到该菜单项的 Click 事件的事件处理程序 (deleteNodeMenuItemClick 方法) 被调用。 在此事件处理程序中,将被单击的节点删除。
在本例中为了实现自定义菜单,使用了 DevExpress.XtraTreeList.Menu.TreeListMenu 类。 该类表示 TreeList 标准上下文菜单的祖先。 如果使用了 XtraBars 库,而不是 TreeListMenu 类,那么可以选择使用提供了设计时刻自定义功能的 PopupMenu 类。
C# | 复制代码 |
---|---|
private void treeList1_MouseDown(object sender, MouseEventArgs e) { // Check if a node's indicator cell is clicked. TreeListHitInfo hitInfo = treeList1.CalcHitInfo(e.Location); TreeListNode node = null; if (hitInfo.HitInfoType == HitInfoType.RowIndicator) { node = hitInfo.Node; } if (node == null) return; // Create a menu with a 'Delete Node' item. TreeListMenu menu = new TreeListMenu(sender as TreeList); DXMenuItem menuItem = new DXMenuItem("Delete Node", new EventHandler(deleteNodeMenuItemClick)); menuItem.Tag = node; menu.Items.Add(menuItem); // Show the menu. menu.Show(e.Location); } // Deletes the node for which the command has been invoked. private void deleteNodeMenuItemClick(object sender, EventArgs e) { DXMenuItem item = sender as DXMenuItem; if (item == null) return; TreeListNode node = item.Tag as TreeListNode; if (node == null) return; node.TreeList.DeleteNode(node); } |
Visual Basic | 复制代码 |
---|---|
Private Sub TreeList1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _ Handles TreeList1.MouseDown ' Check if a node's indicator cell is clicked. Dim hitInfo As TreeListHitInfo = treeList1.CalcHitInfo(e.Location) Dim node As TreeListNode = Nothing If hitInfo.HitInfoType = HitInfoType.RowIndicator Then node = hitInfo.Node End If If node Is Nothing Then Return End If ' Create a menu with a 'Delete Node' item. Dim menu As TreeListMenu = New TreeListMenu(TryCast(sender, TreeList)) Dim menuItem As DXMenuItem = New DXMenuItem("Delete Node", _ New EventHandler(AddressOf deleteNodeMenuItemClick)) menuItem.Tag = node menu.Items.Add(menuItem) ' Show the menu. menu.Show(e.Location) End Sub ' Deletes the node for which the command has been invoked. Private Sub deleteNodeMenuItemClick(ByVal sender As Object, ByVal e As EventArgs) Dim item As DXMenuItem = TryCast(sender, DXMenuItem) If item Is Nothing Then Return End If Dim node As TreeListNode = TryCast(item.Tag, TreeListNode) If node Is Nothing Then Return End If node.TreeList.DeleteNode(node) End Sub |