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
}
You could store that info in the
item.Tagwhen you create it, then in the handler you can just cast thesender(toMenuItem) and retrieve it again.