1

I have a context menu that's bound to a list of strings so that each menuitem's text is an element of the string list. Each menuitem is set to the same event handler. What I'm trying to do is to figure out is which menu item was clicked when when the event handler is called.

I would think it would be pretty straight forward to do, but I'm a bit stumped.

If I look at the watch window, there's a menuitem property called FocusedItem. It has the information I need but when I try to use it it doesn't seem to be part of the class and the code doesn't even compile, which I find strange.

Can someone point me in the right direction?

The bit of xaml and code I'm having trouble with:

<MenuItem Header="Add Object"  ItemsSource="{Binding ObjectClassList}" Click="AddObject_Click"/>

    private void AddObject_Click(object sender, RoutedEventArgs e)
    {
        MenuItem menuItem = sender as MenuItem;

        if (menuItem == null)
        {
            return;
        }

        // menuItem.FocusedItem // ?? does not compile


    }

Thanks!

4

2 回答 2

4

This works for me, but not 100% sure it's the right way (it's on the right path though!)

MenuItem m = (MenuItem)e.OriginalSource;

I belive it's correct, as the "container" menuitem is wrapping up the events for the string menu items you've added. The "OriginalSource" will be the click on the string menu item...

于 2009-07-31T15:24:40.713 回答
2

Some notes that might be helpful when reading the accepted answer by Sk93:

void Handle_RoutedEvent(object sender, RoutedEventArgs e)
  • sender is the logical element that has defined the event handler.
  • RoutedEventArgs.source is the logical element that has defined the event handler.
  • RoutedEventArgs.originalSource is the visual element that the user clicked on.
于 2009-12-08T23:19:09.480 回答