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.
159cd13c-a5d1-40d6-a167-5410b96afbea|1|5.0
Tags:
C# | WPF