How to work with delegates and event handler for user control

我只是一个虾纸丫 提交于 2019-11-29 02:11:22

You can create your own delegate event by doing the following within your user control:

public event UserControlClickHandler InnerButtonClick;
public delegate void UserControlClickHandler (object sender, EventArgs e);

You call the event from your handler using the following:

protected void YourButton_Click(object sender, EventArgs e)
{
   if (this.InnerButtonClick != null)
   {
      this.InnerButtonClick(sender, e);
   }
}

Then you can hook into the event using

UserControl.InnerButtonClick+= // Etc.

It's not necessary to declare a new delegate. In your user control:

public class MyControl : UserControl
{
  public event EventHandler InnerButtonClick;
  public MyControl()
  {
    InitializeComponent();
    innerButton.Click += new EventHandler(innerButton_Click);
  }
  private void innerButton_Click(object sender, EventArgs e)
  {
    if (InnerButtonClick != null)
    {
      InnerButtonClick(this, e); // or possibly InnerButtonClick(innerButton, e); depending on what you want the sender to be
    }
  }
}

Just modernizing ChéDon's answer, here is how you can do it in 2018:

public class MyControl : UserControl
{
  public event EventHandler InnerButtonClick;

  public MyControl()
  {
    InitializeComponent();
    innerButton.Click += innerButton_Click;
  }

  private void innerButton_Click(object sender, EventArgs e)
  {
      InnerButtonClick?.Invoke(this, e);
      //or
      InnerButtonClick?.Invoke(innerButton, e); 
      //depending on what you want the sender to be
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!