thiag0
thiag0

Reputation: 2229

How To Find Name Property Of Parent Element When ContextMenu MenuItem Is Clicked

I have the following code which creates a new Button with a ContextMenu with a single MenuItem called "Remove".

My question is...in the removeItem_Click EventHandler, how do I find out the Name property of the Button that contained this ContextMenu MenuItem?

private Button CreateRdpConnectionButton(string content, string name)
{
    var newButton = new Button();            
    newButton.Content = content;
    newButton.Name = name;
    newButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;

    ContextMenu menu = new ContextMenu();
    MenuItem item = new MenuItem();
    item.Header = "Remove";
    item.Click += removeItem_Click;
    menu.Items.Add(item);

    newButton.ContextMenu = menu;
}

void removeItem_Click(object sender, RoutedEventArgs e)
{
    // TODO: Find name of Button that contained this item
}

Upvotes: 1

Views: 1630

Answers (4)

Touhid Alam
Touhid Alam

Reputation: 343

Store data as <Button Tag=""/> and retrieve the tag as (sender as Button).Tag

Upvotes: 0

CptObvious
CptObvious

Reputation: 376

You could also directly access the parents:

void removeItem_Click(object sender, RoutedEventArgs e)
{
    // Find name of Button that contained this item
    MenuItem    menuItem      = (MenuItem)sender;
    ContextMenu contextMenu   = (ContextMenu)menuItem.Parent;
    Button      button        = (Button)contextMenu.PlacementTarget;

    string buttonName = button.Name;
}

Upvotes: 3

langtu
langtu

Reputation: 1218

Use (MenuItem)sender to access your menu item

Upvotes: 0

brunnerh
brunnerh

Reputation: 184296

You could store that info in the item.Tag when you create it, then in the handler you can just cast the sender (to MenuItem) and retrieve it again.

Upvotes: 0

Related Questions