Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Windows ContextMenu ItemClick Event?

Tags:

c#

.net

wpf

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...

like image 905
Sander Declerck Avatar asked Mar 25 '26 00:03

Sander Declerck


2 Answers

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);
like image 171
Steve Danner Avatar answered Mar 26 '26 14:03

Steve Danner


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

like image 34
Haplo Avatar answered Mar 26 '26 14:03

Haplo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!