Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get click event on a menuitem with subitems (C#)

I am creating a contextmenu that should contain a listing of all folders, subfolders, and files in a chosen folder. I want the menu to open the files and folders when they are clicked, but the click event doesn't register if the menuitem has subitems.

void Foo(string Title)
{
    MenuItem = new MenuItem(Title);
    MenuItem.Click += new EventHandler(MenuItem_Click);
    ContextMenu.MenuItems.Add(MenuItem);
}

void MenuItem_Click(object sender, EventArgs e)
{
    MessageBox.Show("This box will only show when menuitems without subitems are clicked");
}

How can I make the click event fire even if the menuitem has subitems?

like image 955
Erlend D. Avatar asked Aug 09 '09 15:08

Erlend D.


1 Answers

It sounds like a menu may not be the most appropriate UI widget here. I believe the reason you don't get a click event raised is that menu items with submenus are assumed to only expand their children when clicked, rather than executing any other action.

That's likely to be the assumption of the user, too.

This behaviour is mentioned in the documentation for MenuItem.Click:

Note: If the MenuItems property for the MenuItem contains any items, this event is not raised. This event is not raised for parent menu items.

like image 186
Jon Skeet Avatar answered Oct 14 '22 13:10

Jon Skeet