我正在使用C#,我有一个对象列表,我想在上下文菜单中显示所有对象,每个对象都显示为MenuItem
。
单击一个MenuItem时,我想引用MenuItem_Click()
函数中的关联对象。
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?
}
答案 0 :(得分:0)
您可以通过
访问它MenuItem nItem = sender as MenuItem;
答案 1 :(得分:0)
var clickedItem = e.OriginalSource as MenuItem;
MyObject myObj = MyList.Find(o => o.Name == clickedItem.Header);
答案 2 :(得分:0)
适合您当前拥有的代码的快速肮脏黑客:使用Tag
属性。
foreach(MyObject o in MyList)
{
MenuItem item = new MenuItem();
item.Header = o.Name;
item.Tag = o;
item.Click += MenuItem_Click;
menu.Items.add(item);
}
然后你可以这样说:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var myObj = (MyObject)((MenuItem)sender).Tag;
}