I’m using C# and I have a list of objects, and I want to show all the objects in a context menu, each object is shown as a MenuItem.
When one MenuItem is clicked, I want to refer to the associated object in the MenuItem_Click() function.
List<MyObject> MyList = new List<MyObject>();
ContextMenu menu = new ContextMenu();
foreach(MyObject o in MyList)
{
MenuItem item = new MenuItem();
item.Header = o.Name;
item.Click += MenuItem_Click;
menu.Items.add(item);
}
menu.IsOpen=true;
void MenuItem_Click(object sender, RoutedEventArgs e){
// Assume the 5th MenuItem is clicked, I need to refer to the 5th object in MyList
// how to do it?
}
A quick dirty hack that fits the code you currently have: use the
Tagproperty.then you can refer to it this way: