Search code examples
c#winformscontextmenucontextmenustrip

Replicating ContextMenu constructor in ContextMenuStrip


From my research and understanding, the ContextMenuStrip is supposed to be the successor to the ContextMenu and, in the spirit of keeping my code updated and sound, I set out to replace one such instance of a ContextMenu.

Previously, to give a MenuItem a sub-menu of items with click handlers, I was doing something like:

    MenuItem[] clearMenu = {    
                                new MenuItem("All", clear_all_click),
                                new MenuItem("Text", clear_text_click),
                                new MenuItem("Images", clear_images_click),
                                new MenuItem("Audio", clear_audio_click) 
                           };

    notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Clear", clearMenu));

enter image description here

I'm not sure if I'm missing something simple, but how do I achieve similar functionality with a ContextMenuStrip? There is no overloaded constructor for the ToolStripMenuItem that lets you add an array of itself to form a sub-menu. There also isn't a way to add items based on selecting a specific item index from the ContextMenuStrip, like:

 notifyIcon.ContextMenuStrip.Items["Clear"].Add

There is a constructor that let's you instantiate, presumably, a sub-menu with an array of ToolStripItem(s), but it's an abstract class so you can't call it directly.

Thoughts? Or am I not seeing the forest through the trees.


Solution

  • You can do exactly what you want. But to access via keyname, you must set the name:

    ToolStripItem[] newItems = {
                        new ToolStripMenuItem("All", null, DoThis),
                        new ToolStripMenuItem("Text", null, DoThis)
                    };
    
    this.contextMenuStrip1.Items.Add(new ToolStripMenuItem("Clear", null, newItems) {Name="Clear"});
    
    var clearItem = this.contextMenuStrip1.Items["Clear"] as ToolStripMenuItem;