moondaddy

I'm using a single MenuItem click event for all of my menu items. In this event I want to use a switch to determine which MenuItem was clicked and then call the appropriate method. How can I identify which MenuItem was clicked

I add a value to the Name property of the MenuItems, but the MenuItem variable is null below.

private void MenuItem_On_Click(object sender, RoutedEventArgs e)

{

MenuItem mnu = (MenuItem)sender;

switch (mnu.Name)

{

case "mnuAddSeg":

AddLineSegment(thm);

break;

case "mnuRemoveSeg":

RemoveLineSegment(thm);

break;

}

}



Re: Windows Presentation Foundation (WPF) MenuItem Click event. Which menu was clicked?

Mark Betz

That should work fine, so there must be something else going on. For example, in one of my apps I have a MenuItem named MenuGameNew. In the handler if I evaluate:

((MenuItem)sender).Name

Then I will get "MenuGameNew" back. By the way, I tried it both ways in my code:

MenuItem mnu = (MenuItem)sender;
string name = mnu.Name;

string name = ((MenuItem)sender).Name;

The result is the same in both cases.





Re: Windows Presentation Foundation (WPF) MenuItem Click event. Which menu was clicked?

Zhou Yong

Try this instead:
private void MenuItem_On_Click(object sender, RoutedEventArgs e)
{
    MenuItem mnu = (MenuItem)e.OriginalSource;
    switch (mnu.Name)
    {
       case "mnuAddSeg":
           AddLineSegment(thm);
           break;
       case "mnuRemoveSeg":
           RemoveLineSegment(thm);
           break;
    }
}

Sheva





Re: Windows Presentation Foundation (WPF) MenuItem Click event. Which menu was clicked?

Mark Betz

Result is the same in all cases for me.



Re: Windows Presentation Foundation (WPF) MenuItem Click event. Which menu was clicked?

Wolf Schmidt - MSFT

You don't want sender, or e.OriginalSource. You want e.Source.

Assuming you had the following:

<Menu MenuItem.Click="CommonHandler">

<MenuItem Header="One" Name="One"/>

<MenuItem Header="Two" Name="Two"/>

<MenuItem Header="Three" Name="Three"/>

</Menu>

... and this ...

void CommonHandler(object sender, RoutedEventArgs e) {

MenuItem mi = e.Source as MenuItem;

switch (mi.Name) {

case "One": { //do something;

break; }

case "Two": { //do something else

break; }

case "Three": { //something else again

break; }

}

}

sender would be the handling point (Menu in this case ... no Name). e.OriginalSource would be some composited element, which is generally something you don't care about when handling menus, or that you care about in general at the application level (mostly, only control authors care about OriginalSource). It's probably a TextBlock with null content, you could try typeof if you're curious.




Re: Windows Presentation Foundation (WPF) MenuItem Click event. Which menu was clicked?

Nathan Neitzke

Or you could use commands.  But yes, you want to you use e.Source, not OriginalSource or sender.