How to add a separator to a WinForms ContextMenu?

Viewed 81908

Inside my control, I have:

ContextMenu = new ContextMenu();
ContextMenu.MenuItems.Add(new MenuItem("&Add Item", onAddSpeaker));
ContextMenu.MenuItems.Add(new MenuItem("&Edit Item", onEditSpeaker));
ContextMenu.MenuItems.Add(new MenuItem("&Delete Item", onDeleteSpeaker));
ContextMenu.MenuItems.Add( ??? );
ContextMenu.MenuItems.Add(new MenuItem("Cancel"));

How to add a separation line to this ContextMenu?

8 Answers

In WPF:

ContextMenu.MenuItems.Add(new Separator());

Horizontal separators are cool, but what if you want a vertical separator instead?

Well, worry ye not - you can have one!

Set BarBreak property to true on the MenuItem which should be the first one after the seperator:

var item = new MenuItem(text: "Settings", onClick: SomeFunction) { BarBreak = true };

enter image description here

To add the item to a MenuItems collection: yourContextMenu.MenuItems.Add(item).

ContextMenu has a constructor which receives an array of MenuItem objects. Needless to say, you can't add a string to that array. You can however get a seperator by adding a new MenuItem("-"):

    var contextMenu = new ContextMenu(new[]
    {
        timerMenuItem,
        keypressMenuItem,
        new MenuItem("-"), // Seperator
        new MenuItem(text: "Exit", onClick: (sender, args) => Application.Exit())
    });
Related