【问题标题】:Assign Methods to Events with Array C#使用数组 C# 为事件分配方法
【发布时间】:2020-12-07 13:18:16
【问题描述】:

我正在使用 WPF C# VS。

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

例如:

1. 按钮将所有其他按钮染成红色。 2. 按钮打开一个新窗口。 3. 按钮显示一个消息框。 ... 每个人都在做其他事情!

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

它应该像这样工作:

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() {...}
...

我希望你能理解我的问题,我的英语不太好。

【问题讨论】:

  • Action代替Method?
  • 或者EventHandler ?

标签: c# events methods


【解决方案1】:

我建议是这样的:

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() {...}

...

【讨论】:

    【解决方案2】:

    我自己解决了:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 2013-11-15
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      相关资源
      最近更新 更多