Skip to main content

How to: Create a custom context menu

  • 2 minutes to read

The empty area does not provide a predefined context menu. You can handle the tree list’s PopupMenuShowing or MouseDown event to show a context menu in the empty area. The code below uses the MouseDown event that fires when a mouse button is pressed. The event handler adds the Add Node command that creates a new node. For an example of how to handle the PopupMenuShowing event, see Empty Area Context Menu.

image

The TreeList.CalcHitInfo method in the event handler returns internal information about the clicked visual element. If the empty area is clicked, the menu is created and the Add Node command is added to the menu. The DXMenuItem.Click event handler creates a new node.

using DevExpress.Utils.Menu;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Menu;
using DevExpress.XtraTreeList.Nodes;

private void treeList1_MouseDown(object sender, MouseEventArgs e) {
    TreeListHitInfo hitInfo = treeList1.CalcHitInfo(e.Location);
    TreeListNode node = null;
    if (hitInfo.HitInfoType == HitInfoType.Empty) {
        // Create a menu with the Add Node command.
        TreeListMenu menu = new TreeListMenu(sender as TreeList);
        DXMenuItem menuItem = new DXMenuItem("Add Node", new EventHandler(addNodeMenuItemClick));
        menu.Items.Add(menuItem);
        // Show the menu.
        menu.Show(e.Location);
    }
}

private void addNodeMenuItemClick(object sender, EventArgs e) {
    treeList1.Nodes.Add("555", "555", "555", "New Department", "10000", "New Location");
}

Tip

The example uses the DevExpress.XtraTreeList.Menu.TreeListMenu type that is a default type for tree list menus. You can also use a PopupMenu object that provides design-time customization capabilities.