Sander Declerck
Sander Declerck

Reputation: 2535

System.Windows ContextMenu ItemClick Event?

I'm making a WPF application, but in my code I need to make a ContextMenu, it seemed really easy:

_menu = new ContextMenu();
_menu.Items.Add("My menu item");

Then I used it, and everything works like a charm.

However, I need to know when "My menu item" is clicked, but I can't seem to find the right event, I'm searching for something like ItemClick event, but cant't find it...

Upvotes: 2

Views: 3526

Answers (3)

Haplo
Haplo

Reputation: 1368

I never did it in code, always used XAML. However, it is something like this:

 _menu = new ContextMenu();
 MenuItem mi = new MenuItem();
 mi.Items.Add("My menu item");
 mi.Click += (sender,args) =>
 {
         // Do what you want, or instead of a lambda  
         // you can even add a separate method to the class
 };
 _menu.Items.Add(mi);

The only doubt is adding the text to the menu item. You'll have to try as in the example or maybe add a TextBlock to the MenuItem.Items collection

Upvotes: 3

dkackman
dkackman

Reputation: 15559

I think you want something like this:

    _menu = new ContextMenu();
    MenuItem item = new MenuItem();
    item.Header = "My menu item";
    item.Click += new RoutedEventHandler(item_Click);
    _menu.Items.Add(item);

Upvotes: 1

Steve Danner
Steve Danner

Reputation: 22158

Try adding an item that is clickable rather than just a string. For example:

_menu = new ContextMenu();
MenuItem item = new MenuItem();
item.Click += MyClickHandler;
item.Header = "My Menu Item";
_menu.Items.Add(item);

Upvotes: 6

Related Questions