Reputation: 2229
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
Reputation: 343
Store data as <Button Tag=""/>
and retrieve the tag as (sender as Button).Tag
Upvotes: 0
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
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