单击 X 后从 UserControl 访问值

Access values from UserControl after clicking on X

我有一个 class 这是一个 UserControl:

public partial class MyView : System.Windows.Forms.UserControl

此界面有各种组件供用户输入。为了显示我遇到的问题,只需要显示一个,所以,in MyView.Designer.cs:

internal System.Windows.Forms.TextBox txtMyNumber;

一开始是空白的。然后用户在 TextBox 中输入一个数字。
然后用户点击右上角的X,调用MyView.OnClose():

protected void OnClose()
{
    string myNumber = txMyNumber.Text;
}

这里我想检查一下有没有输入数据。但是,txtMyNumber 并没有显示用户输入的内容,它仍然是空白。所以当用户点击 X 时它会出现,它不在表单中并且不知道输入的值。
如何访问这些值?

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this.OnClose();

        if (_presenter != null)
            _presenter.Dispose();

        if (components != null)
            components.Dispose();
    }

    base.Dispose(disposing);
}

我会尝试使用窗体的 FormClosing 事件来检查 UserControl 状态。

在用户控件中,添加一个函数,如下所示:

public bool UserControlOK() {
  return !string.IsNullOfEmpty(txMyNumber.Text);
}

然后在表单中,检查事件覆盖中的值:

protected override void OnFormClosing(FormClosingEventArgs e) {
  if (!myView1.UserControlOK()) {
    MessageBox.Show("TextBox is empty.");
    e.Cancel = true;
  }

  base.OnFormClosing(e);
}

另一种方法是订阅容器Form的FormClosing事件,保存父Form开始关闭时需要保存的内容 进程。
可以在用户控件的 Load() 事件中订阅表单的事件,因此您确定所有句柄都已创建:

private Form MyForm = null;

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    this.MyForm = this.FindForm();
    this.MyForm.FormClosing += this.OnFormClosing;
}

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    Console.WriteLine("My Form is closing!");
    string myNumber = txMyNumber.Text;
}

如果 UC 需要了解有关其表单的其他信息,则此方法更有用。

另一种非常相似的方法是订阅用户控件的 OnHandleDestroyed 事件。

protected override void OnHandleDestroyed(EventArgs e)
{
    Console.WriteLine("I'm being destroyed!");
    string myNumber = txMyNumber.Text;

    base.OnHandleDestroyed(e);
}