简体   繁体   中英

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

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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