user569574
user569574

Reputation: 99

how to get parent name of a context menu item?

I'm trying to get the parent name of a context menu item.

So I tried something like this on menuItem_click :

Button clikance = (Button)sender;
string ladyGaga = Convert.ToString(clikance.Content);

But it didn't work (invalid cast exception). thx for any help

Upvotes: 1

Views: 2012

Answers (3)

user569574
user569574

Reputation: 99

i have use a different approach for getting the sender button of my context menu. i have made an event on the "hold_click"

where i have get back the content of the button in a public string

private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
{
    Button clikance = (Button)sender;
    ButtonEnvoyeur = Convert.ToString(clikance.Content);
}

Upvotes: 2

Jean-Alexis Aufauvre
Jean-Alexis Aufauvre

Reputation: 828

Use the Tag property of the MenuItem to retrieve your Button :

// Object creation
Button myButtonWithContextMenu = new Button();
ContextMenu contextMenu = new ContextMenu();
MenuItem aMenuItem = new MenuItem 
{
    Header = "some action",
    Tag = myButtonWithContextMenu, // tag contains the button
};

// Events handler
aMenuItem.Click += new RoutedEventHandler(itemClick);

private void itemClick(object sender, RoutedEventArgs e)
{
    // Sender is the MenuItem
    MenuItem menuItem = sender as MenuItem;

    // Retrieve button from tag
    Button myButtonWithContextMenu = menuItem.Tag as Button;
    (...)         
}

Alex.

Upvotes: 1

Derek Lakin
Derek Lakin

Reputation: 16319

If you look in the debugger at the point where the exception is raised, you'll see that sender isn't a Button, so trying to do an explicit cast to Button will obviously throw an InvalidCastException.

You can use the VisualTreeHelper to walk up the tree from your actual sender to the Button element:

VisualTreeHelper.GetParent((sender as DependencyObject));

UPDATE: In your instance sender is the MenuItem in the ContextMenu. You can get to the parent ContextMenu from the MenuItem by using the VisualTreeHelper, but unfortunately, ContextMenu does not expose any public members that enable you to access the owner; the Owner property is internal. You could get the source code for the Toolkit and expose the Owner property as publi instead, or use a completely different approach.

Have you thought of using an MVVM framework (such as MVVM Light) to wire up commands to these context menu items? Your current approach is very fragile and will break as soon as you change the visual tree. If you used commands, you could pass any additional information that you need for processing via the command parameter.

Upvotes: 1

Related Questions