Pass click event of child control to the parent control

后端 未结 1 1662
北海茫月
北海茫月 2020-11-29 09:00

I have a Windows form, having a pane, which contains another class, derived from Windows Forms. This is contained as a control within the pane. It contains two buttons withi

相关标签:
1条回答
  • 2020-11-29 09:29

    While you can interact with parent form directly from child, It's better to raise some events by child control and subscribe for the events in parent form.

    Raise event from Child:

    public event EventHandler CloseButtonClicked;
    protected virtual void OnCloseButtonClicked(EventArgs e)
    {
        var handler = CloseButtonClicked;
        if (handler != null)
            handler(this, e);
    }
    private void CloseButton_Click(object sender, EventArgs e)
    {
        //While you can call `this.ParentForm.Close()` it's better to raise an event
        OnCloseButtonClicked(e);
    }
    

    Subscribe and use event in Parent:

    //Subscribe for event using designer or in form load
    this.userControl11.CloseButtonClicked += userControl11_CloseButtonClicked;
    
    //Close the form when you received the notification
    private void userControl11_CloseButtonClicked(object sender, EventArgs e)
    {
        this.Close();
    }
    

    To learn more about events, take a look at:

    • Handling and raising events
    • Standard .NET event pattern
    0 讨论(0)
提交回复
热议问题