如何创建将多个事件处理程序附加到多个控件的函数? [英] How can I create a function that attaches multiple event handlers to multiple controls?

查看:87
本文介绍了如何创建将多个事件处理程序附加到多个控件的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
如何创建将多个事件处理程序附加到多个控件的函数?

意图:
我正在使用C#开发Windows窗体应用程序.我想创建一个函数,它接受控件和事件处理程序的集合.此函数会将事件处理程序附加到控件.什么是做到这一点的最优雅,最可重用的方法.我对委托人有一个丑陋的方法,但这是一个麻烦的工作,但是将其放入一个循环并放弃该函数对我来说却较少.

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.

我基本上想要的行为:

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


功能:
attachHandlers(? controlCollection, ? eventHandlers)


我只是要将所有处理程序都订阅到所有控件上的同一事件.我在说明中没有明确地说过这一点,所以我相信这是造成所有混乱的原因.


Function:
attachHandlers(? controlCollection, ? eventHandlers)


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.

推荐答案

如果有问题的控件继承自相同的基类或接口(或者它们是同一类),则可以执行以下操作:

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

这假定一个接口,如:

public interface IClickableControl
{
    event MyClickHandler Click;
}

这篇关于如何创建将多个事件处理程序附加到多个控件的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆