views:

571

answers:

1

Is there a way for a parent MenuItem to be notified when a child MenuItem is pressed. For example, I you have

<MenuItem Name='a'>
    <MenuItem Name='b' Header='...'/>
</MenuItem>

how can I add an event handler to a to be notified when b is clicked. Ideally, the Click event would be either a tunnel or bubble event but this is not the case. The solution I have in mind is to listen to the Click event on b and forward it to a but this seems pretty heavy handed. Is there a better solution?

+3  A: 

MenuItem.Click is a routed event (it bubbles up), so you can just subscribe to it on the first MenuItem and be notified of all children at the same time.

XAML:

<MenuItem Name='a' Click='OnMenuItemClicked'>
    <MenuItem Name='b' Header='...' />
</MenuItem>

C#:

private void OnMenuItemClicked(object sender, RoutedEventArgs e)
{
    MenuItem item = e.OriginalSource as MenuItem;
    if(null != item)
    {
        // Handle the menu item click here
    }
}

The trick is to use RoutedEventArgs.OriginalSource, rather than sender. This points to the control that originally fired the event.

Andy
you are right. It is a bubble event.
tom7