Daniel Peñalba
Daniel Peñalba

Reputation: 31897

C#: How to add a full ContextMenu to MenuItem as a submenu

Using .NET and Windows Forms:

What is the sortest way to add a full ContextMenu to a MenuItem?

I mean:

private void AddSubMenu(MenuItem item, ContextMenu menu)
{
   // I want to add the full menu to the menu item as a submenu

   // I could iterate the items of the menu and add them to the item
   // but I guess that there is a smarter way to do this
}

Thanks in advance.

Upvotes: 2

Views: 3432

Answers (2)

digEmAll
digEmAll

Reputation: 57220

Actually, that's really simple:

private void AddSubMenu(MenuItem item, ContextMenu contextMenu)
{
    item.MergeMenu(contextMenu);
}

and obviously, all the event handlers subscribed before the merge will still work and will be triggered by both menus.

Upvotes: 4

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

Well i didn't found any much smarter way then iterating strategy. However you can leave that to AddRange function. So your code becomes.

private void AddSubMenu(MenuItem item, ContextMenu menu)
{
    item.MenuItems.AddRange(menu.MenuItems);
}

MenuItems return a MenuItemCollection and Addrange Takes such Collection so both satisfied and we are save from doing the Iteration stuff.

Upvotes: 0

Related Questions