我有一个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时,它出现在Form下,并且不知道输入的值。
如何访问这些值?
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.OnClose();
if (_presenter != null)
_presenter.Dispose();
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
另一种方法是订阅容器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需要了解其表单的其他内容,则此方法更有用。
另一种非常相似的方式是订阅用户控件qazxsw poi事件。
OnHandleDestroyed
我会尝试使用窗体的FormClosing事件来检查UserControl状态。
在UserControl中,添加一个函数,如下所示:
protected override void OnHandleDestroyed(EventArgs e)
{
Console.WriteLine("I'm being destroyed!");
string myNumber = txMyNumber.Text;
base.OnHandleDestroyed(e);
}
然后在表单中,检查事件覆盖中的值:
public bool UserControlOK() {
return !string.IsNullOfEmpty(txMyNumber.Text);
}