使用用户控件 C# 触发事件

Trigger an event using user Control C#

假设如果我在自定义的用户控件上有一个按钮,该按钮从它所在的表单(我们称之为 formX)中删除该控件。

private void btnClose_Click(object sender, EventArgs e)
{
    this.ParentForm.Controls.Remove(this);
}

现在,在关闭此 UserControl 后,我希望调用 formX 中的一个方法。

我试过这样做:

discount.ControlRemoved += new ControlEventHandler(discount_ControlRemoved);

void UserControl_ControlRemoved(object sender, ControlEventArgs e)
{
    CallMethod();
}

但是这不起作用,当从 formX 中删除 userControl 时,甚至在调试器中都不会调用该事件。

我该怎么做?

您应该使用的事件是父容器上的 ControlRemoved 事件,在本例中可能是 Form。您可以通过多种方式执行此操作,有些可能比其他方式更好,具体取决于您想要做什么,但以下至少应该满足您的要求:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.ControlRemoved += new ControlEventHandler(Form1_ControlRemoved);
    }

    void Form1_ControlRemoved(object sender, ControlEventArgs e)
    {
        if (e.Control.Name == "NameOfUserControl") CallMethod();
    }

    private void CallMethod()
    {
        // Do stufff...
    }
}

这假定您已将 User Control 实例命名为 "NameOfUserControl"。有多种方法可以检查要删除的控件是否正确。您还可以通过在控件本身中执行此操作,同时使用委托回调父窗体等来使其更加动态...这只是一个基本示例。