开发者

Custom Control Events in C#

I'm trying to create a custom control and need to raise an event from it. The idea is to raise an event at the end of the click event (OnAfterClick). I found one or two tutorials on doing this, but am clearly missing a step somewhere; I have the following.

In the control:

public class AfterClickEventArgs : EventArgs
{
  ...
}

public partial class MyButton : CommandButton
{
    public delegate void AfterClickEvnt(object sender, AfterClickEventArgs e);

    public event AfterClickUpdatedEvnt AfterClick;

}

protected override void OnClick(EventArgs e)
{
    ...
    Processing here
    ...

    AfterClickEventArgs myArgs = new AfterClickEventArgs();                
    AfterClick(this, myArgs);
}

In the program using the control:

In InitializeComponent():

this.MyButt开发者_C百科on.AfterClick += new System.EventHandler(this.cmdMyButton_Click);

This line is giving me a compile error (cmdMyButton_Click does exist). It tells me: Cannot implicitly convert type 'System.EventHandler' to 'Namespace.MyButton.AfterClick'

Can anyone tell me what I'm missing, or misunderstanding about this, please?


Your event is declared to be of type AfterClickEvnt, but you're trying to subscribe to it using an EventHandler. You can't convert between the two.

Options:

  • Explicitly state the right type:

    this.MyButton.AfterClick += new AfterClickEvnt(this.cmdMyButton_Click);
    
  • Use an implicit method group conversion:

    this.MyButton.AfterClick += cmdMyButton_Click;
    

By the way, I suggest you remove your custom delegate type and instead use the generic EventHandler<T> delegate:

public event EventHandler<AfterClickEventArgs> AfterClick;


There is some discrepancies in your code, so it's hard to say what is going on. (myArgs became newArgs, and AfterClickUpdateEvnt became AfterClickEvnt). You also attempt to use an EventHandler in place of your delegate.

Also, it's better to use EventHandler<T> so that you don't have to bother with a delegate:

public event EventHandler<AfterClickEventArgs> AfterClick;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜