How can I create a function that attaches multiple event handlers to multiple controls?

空扰寡人 提交于 2019-12-11 09:45:01

问题


Question:
How can I create a function that attaches multiple event handlers to multiple controls?

Intent:
I am using C# to develop a windows forms application. I want to create a function that takes a collection of controls and a collection of event handlers. This function will attach the event handlers to the controls. What would be the most elegant, and reusable way to do this. I have a pretty ugly way to do this with delegates, but it is a but it is less work for me to just throw this into a loop, and abandoning the function.

Behavior I basically want:

foreach(Control control in controlCollection)
     foreach(EventHandler handler in eventHandlerCollection)
                    control.Event += handler;


Function:
attachHandlers(? controlCollection, ? eventHandlers)

Edit:
I am just going to subscribe all the handlers to the same event on all the controls. I didn't explicitly say that in my description, so I believe that is the reason for all of confusion.


回答1:


If the controls in question inherit from the same base class or interface (or they are the same class), you can do something like:

void AttachClickEventHandlers(List<IClickableControl> controls, List<MyClickHandler> eventHandlers)
{
    foreach (var control in controls)
        foreach (MyClickHandler handler in eventHandlers)
            control.Click += handler;
}

This assumes an interface like:

public interface IClickableControl
{
    event MyClickHandler Click;
}


来源:https://stackoverflow.com/questions/10953160/how-can-i-create-a-function-that-attaches-multiple-event-handlers-to-multiple-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!