3

I'm using a code for get the name of the control that fire the ContextMenu, but the compiler return this message on this line: ContextMenu menu = menuItem.GetContextMenu();

MenuItem does not contain a definition of GetContextMenu and found no extension method 'GetContextMenu' accepting a first argument of type 'MenuItem'. Probably missing a using directive or an assembly reference.

The same error here:

Control sourceControl = menu.SourceControl;

This is my method:

private void ClearTable_Click(object sender, RoutedEventArgs e)
    {
        // Try to cast the sender to a MenuItem
        MenuItem menuItem = sender as MenuItem;
        if (menuItem != null)
        {
            // Retrieve the ContextMenu that contains this MenuItem
            ContextMenu menu = menuItem.GetContextMenu();

            // Get the control that is displaying this context menu
            Control sourceControl = menu.SourceControl;
        }
    }

Which library I must to add?

Bender
  • 523
  • 6
  • 21

1 Answers1

1

.GetContextMenu() is a method of the Menu class in System.Windows.Forms namespace (in System.Windows.Forms.dll). Therefore it's not designed to work on WPF controls... although with some tweaking it may be possible.

If you're doing this in WPF, you'll want to use ContextMenu class in the System.Windows.Controls namespace, with its methods.

Aaron Thomas
  • 5,054
  • 8
  • 43
  • 89
  • I've used: ContextMenu menuItem = sender as ContextMenu; but same error returned.. – Bender Aug 21 '15 at 13:26
  • ContextMenu exists as a class in both namespaces I listed in my error, so `ContextMenu menuItem = sender as ContextMenu;` would work. The trouble is, your code is now using the `ContextMenu` in `System.Windows.Controls` namespace - which does not have a `.GetContextMenu()` method. – Aaron Thomas Aug 21 '15 at 13:31
  • Okay, but there's an alternative method to GetContextMenu();? – Bender Aug 21 '15 at 13:44
  • I want just get the name of the control that has fired an event through ContextMenu, like this: http://stackoverflow.com/questions/4886327/determine-what-control-the-contextmenustrip-was-used-on – Bender Aug 21 '15 at 13:48
  • Yep, so that is definitely outside the scope of this question, but off the top of my head I'm thinking of using something like the `Parent` property of the sender argument. – Aaron Thomas Aug 21 '15 at 13:50
  • I've another question opened here: http://stackoverflow.com/questions/4886327/determine-what-control-the-contextmenustrip-was-used-on If you want take a look, thanks. – Bender Aug 21 '15 at 13:51
  • okay. if you think my answer answered this question, please mark it as answered. – Aaron Thomas Aug 21 '15 at 14:02
  • Okay, could you help me in the another question, please? – Bender Aug 21 '15 at 14:03