将方法分配给数组为C#的事件



我使用的是WPF C#VS

我必须创建大约100个按钮,每个按钮都应该有自己的事件。我也不想自己创建它们。

例如:

1。按钮将所有其他按钮染成红色。2。按钮打开一个新窗口。3。按钮显示一个MessageBox。。。。每个人都做别的事!!

所以问题是如何将方法存储在数组中?

它应该是这样工作的:

List<Button> buttons = new List<Button>();    //Contains all buttons
void fillButtonsList() {...}                  //Storing Buttons in list
Method[] methods = new Method[]               //Storing Methods in Arrays
{
colorAll,
openWindow,
showMessageBox,
...
}
void ApplyEvents()                            //Assign Methods to Events
{
for (int i = 0; i < methods.Length; i++)
{
buttons[i].Click += methods[i];
}
}
void colorAll() {...}                         //Methos get Executed when Event got Fired
void openWindow() {...}
void showMessageBox() {...}
...

我希望你能理解我的问题——我的英语不是很好。

我建议这样做:

List<Button> buttons = new List<Button>();    //Contains all buttons
void fillButtonsList() {...}                  //Storing Buttons in list
Action[] methods = new Action[]               //Storing Methods in Arrays
{
colorAll,
openWindow,
showMessageBox,
...
}
void ApplyEvents()                            
{
for (int i = 0; i < methods.Length; i++)
{
buttons[i].Click += (s, e) => methods[i].Invoke();
}
}
void colorAll() {...}                         
void openWindow() {...}
void showMessageBox() {...}

我自己解决了:

ContextMenu cm1 = new ContextMenu();
(string, bool, ContextMenu, RoutedEventHandler)[] ContextMenuInfo = new (string, bool, ContextMenu, RoutedEventHandler)[]
{
("1", false, cm1, event1),
("2", false, cm1, event2),
("3", false, cm1, event3),
("4", false, cm1, event4),
("5", false, cm1, event5)
};
foreach ((string, bool, ContextMenu, RoutedEventHandler) item in ContextMenuInfo)
{
MenuItem mi = MakeContextMenuMenuItem(item.Item1, item.Item2);
mi.Click += item.Item4;
item.Item3.Items.Add(mi);
}
void event1() {...}
void event2() {...}
void event3() {...}
void event4() {...}
void event5() {...}
private MenuItem MakeContextMenuMenuItem(string text, bool bold = false)
{
TextBlock tbb = new TextBlock();
if (bold)
{
tbb.Inlines.Add(new Bold(new Run(text)));
}
else
{
tbb.Text = text;
}
MenuItem mi = new MenuItem();
mi.Header = tbb;
return mi;
}

最新更新