简体   繁体   English

按钮的自定义EventHandler

[英]Custom EventHandler for a button

I want to assign a custom event handler to a button. 我想将自定义事件处理程序分配给按钮。

I made an event handler as under 我做了一个事件处理程序如下

public class ButtonEventHandler
{
    ButtonEventHandler()
    {
        // Assign a function to delegate
        this.ClickHandler = _ClickHandler;
    }

    public delegate void ClickHandlerDelegate(object sender, EventArgs e);
    public ClickHandlerDelegate ClickHandler;
    private void _ClickHandler(object sender, EventArgs e)
    {

    }
}

I then assigned it to the Button, inside the constructor of another class 然后,将其分配给另一个类的构造函数中的Button

public ImgButton(Image image, string lblTxt, ButtonEventHandler eventHandler)
{
    InitializeComponent();

    this.lblTxt.Click      += eventHandler.ClickHandler;
}

When I try to compile, I get below error 当我尝试编译时,出现以下错误

Error Cannot implicitly convert type 'ClickHandlerDelegate' to 'System.EventHandler' 错误无法将类型'ClickHandlerDelegate'隐式转换为'System.EventHandler'

What to do ? 该怎么办 ? Can delegates be inherited ? 可以继承代表吗? If yes, how ? 如果是,怎么办? if not, then how to explicitly convert ? 如果没有,那么如何显式转换?

You dont need create delegate object, just create method as public and handle it to click event 您不需要创建委托对象,只需将方法创建为公共方法并处理它以单击事件

public class ButtonEventHandler
{    
    public void ClickHandler(object sender, EventArgs e)
    {

    }
}

Also you can create it as static if don't want to create instance object 如果不想创建实例对象,也可以将其创建为静态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM