How to work with delegates and event handler for user control

前端 未结 3 817
说谎
说谎 2020-12-16 04:42

I have created a user control that contains a button. I am using this control on my winform which will be loaded at run time after fetching data from database.

Now I

相关标签:
3条回答
  • 2020-12-16 05:00

    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.
    
    0 讨论(0)
  • 2020-12-16 05:02

    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
      }
    }
    
    0 讨论(0)
  • 2020-12-16 05:06

    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
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题