我希望在关闭表单 2 时刷新表单 1。我知道使用 form2 的结束事件,但这就是我迷路的地方。
谢谢
最佳答案
实现此目的的一个好方法是使用中介者模式。通过这种方式,您的表单不必相互了解。允许 Mediator 管理表单之间的交互,以便每个单独的表单都可以专注于自己的职责。
一个非常粗糙的调解器可以实现你想要的,可以像这样实现:
public class FormMediator
{
public Form MainForm { private get; set; }
public Form SubForm { private get; set; }
public void InitializeMediator()
{
MainForm.FormClosed += MainForm_FormClosed;
}
void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
SubForm.Refresh();
}
}
现在,只要主表单关闭,您的子表单就会更新,并且彼此之间无需了解任何信息。
编辑:
好的,所以我将提出这个解决方案,让您入门,但请注意,这只是中介者模式的基本实现。我强烈建议您阅读有关该模式和一般设计模式的内容,以便更好地了解正在发生的事情。
同样,这是一个示例,但它确实有一些基本的错误检查,应该可以让你继续。
您的表单声明将如下所示:
public partial class MainForm : Form
{
private FormMediator _formMediator;
public MainForm()
{
InitializeComponent();
}
public void SomeMethodThatOpensTheSubForm()
{
SubForm subForm = new SubForm();
_formMediator = new FormMediator(this, subForm);
subForm.Show(this);
}
}
Mediator 的修改后的实现如下所示:
public class FormMediator
{
private Form _subForm;
private Form _mainForm;
public FormMediator(Form mainForm, Form subForm)
{
if (mainForm == null)
throw new ArgumentNullException("mainForm");
if (subForm == null)
throw new ArgumentNullException("subForm");
_mainForm = mainForm;
_subForm = subForm;
_subForm.FormClosed += MainForm_FormClosed;
}
void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
_mainForm.Refresh();
}
catch(NullReferenceException ex)
{
throw new InvalidOperationException("Unable to close the Main Form because the FormMediator no longer has a reference to it.", ex);
}
}
}
关于c# - 关闭form2时如何让form1刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/930845/