Adding a handler to menus in WPF to handle MenuItem Clicks

by mheydt 18. February 2008 17:07 >
Here's a little code note to everyone that might want to handle the click events in a menu for all menuitems in a single method of the parent menu instead of either declaring one for each menuitem.  I like this as it's a centralized way of managing all these events, and works out well when you have dynamic menuitems and therefore can't declaratively define an event handler for them.

How this works is that the Click event of a menu item is a bubbled event, and therefore if it is not handled by the menuitem itself, the event will propagate up the tree to the parent control, which happens to be the menu.  However, the menu class does not have a 'Click' event to override (either programmatially or in XAML), so how do you do it?

Fairly simply it turns out.  in the menu you can add a handler with the 'AddHandler' method (convenient name), specifying which type of routed event you want to handle and what method to use to handle it.  So for example if you have a 'Menu' by the name of 'menu', the following code will hook up a handler to intercept all Click events on all MenuItem's that are children of that menu:

// this is a user control that has a 'Menu' object named 'menu' declared in its xaml

public MainMenu() 
{
    InitializeComponent();

    menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(menuItem_Click));
}

public void menuItem_Click(object sender, RoutedEventArgs e)
{
    e.Handled = true;
}

The e.Handled = true code prevents the event from being bubbled up further.  Pretty simple and handy, no?  I really like these bubbled events as it's a much better model for event processing than in Win32 or WinForms.

Tags:

C# | WPF

blog comments powered by Disqus

about the author

I'm a .NET, XAML, and iOS polyglot that loves playing with new things and making cool and innovative stuff.  I am also a Mac junkie.

I am Principal Technologist for SunGard Global Services in NYC, in their Advanced Technologies practice, and I work extensively with SunGard's energy and financial customers.

Note the the posting on this blog are my own and do not represent the position, strategies or opinions of SGS.

twitter

I can't stop thinking big!
Sunday 1:08AM via WindowsLive
Just watched Moneyball. That's my pick for best movie this year.
Saturday 3:51PM via WindowsLive
@vincebelpiede: Report: Skype For Windows Phone Beta Imminent http://t.co/KYNjgg1L#mhtnd
Wednesday 8:39AM via Twitter for Mac
@mashable: Kinect Fusion Will Turn Gaming (and More) Into a 3D Fun House - http://t.co/Ihrq2fY2#mhtnd
Wednesday 8:39AM via Twitter for Mac
New Kinect SDK: http://t.co/57MvA5L5 #mhtnd
Wednesday 8:39AM via Twitter for Mac
Follow me on Twitter

recent comments

None

month list