我使用 ShowDialog 将表单作为模式对话框打开。该对话框反过来允许使用 ShowDialog 再次将另一个表单作为模式对话框打开。
当最里面的对话框关闭时,这会导致其父对话框也关闭。为什么会发生这种情况,我该如何预防?
我创建了一个问题的 hello world 版本来说明这一点。
表格一:
private void OpenForm2Button_Click(object sender, EventArgs e)
{
Form2 testForm = new Form2();
DialogResult dialogResult = new DialogResult();
dialogResult = testForm.ShowDialog();
MessageBox.Show("Form 2 returned: " + Convert.ToString(dialogResult));
}
表格 2:
...
this.Form2OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Form2CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
...
this.AcceptButton = this.Form2OKButton;
this.CancelButton = this.Form2CancelButton;
...
private void OpenForm3Button_Click(object sender, EventArgs e)
{
Form3 testForm = new Form3();
DialogResult dialogResult = new DialogResult();
dialogResult = testForm.ShowDialog();
MessageBox.Show("Form 3 returned: " + Convert.ToString(dialogResult));
}
表格 3:
...
this.Form3OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Form3CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
...
this.AcceptButton = this.Form3OKButton;
this.CancelButton = this.Form3CancelButton;
重现步骤:
- 点击“打开表格2”
- 点击“打开表格 3”
- 点击“取消”
表格 3 按预期以 DialogResult == Cancel 关闭,但表格 2 也以 DialogResult == Cancel (非预期)关闭。