3 回答
TA贡献1784条经验 获得超8个赞
static避免类和全局引用几乎总是 100% 更好。
最好传递一个Action<FormC>允许您通知FormC即将关闭的消息。
尝试这个:
FormA
public partial class FormA : Form
{
public FormA()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var formB = new FormB(this.ClosingC);
formB.Show();
}
private void ClosingC(FormC formC)
{
MessageBox.Show("Closing C");
}
}
FormB
public partial class FormB : Form
{
public FormB()
{
InitializeComponent();
}
private Action<FormC> _closingFormC = null;
public FormB(Action<FormC> closingFormC)
: this()
{
_closingFormC = closingFormC;
}
private void Button1_Click(object sender, EventArgs e)
{
var formC = new FormC(_closingFormC);
formC.Show();
}
}
FormC
public partial class FormC : Form
{
public FormC()
{
InitializeComponent();
}
private Action<FormC> _closingFormC = null;
public FormC(Action<FormC> closingFormC)
: this()
{
_closingFormC = closingFormC;
}
private void FormC_FormClosing(object sender, FormClosingEventArgs e)
{
_closingFormC?.Invoke(this);
}
}
TA贡献1898条经验 获得超8个赞
我会使用事件聚合。这是一个小的Install-Package Caliburn.Micro.EventAggregator
曾经像
public class MyForm : Form, IHandle<MyEvent>
{
public MyForm()
{
SomeStaticPlace.EventAggregator.Subscribe(this); //Can be replaced with DI
}
public void Handle(MyEvent message)
{
//Act on event
}
}
并发布SomeStaticPlace.EventAggregator.Publish(new MyEvent(...));
TA贡献1829条经验 获得超13个赞
这是带有静态事件的全局静态类FormClosed:
public static class GlobalStaticClass
{
public static event FormClosedEventHandler FormClosed;
public static void OnFormClosed(object sender, FormClosedEventArgs e)
{
FormClosed?.Invoke(sender, e);
}
}
这是FormC。引发FormClosed事件:
public partial class FormC : Form
{
public FormC()
{
InitializeComponent();
this.FormClosed += (sender, e) =>
{
GlobalStaticClass.OnFormClosed(sender, e);
};
}
}
这是FormA听这个事件的:
public partial class FormA : Form
{
public FormA()
{
InitializeComponent();
GlobalStaticClass.FormClosed += (sender, e) =>
{
//if (sender is FormC)
MessageBox.Show(((Form)sender).Name + " Closed, reason: " + e.CloseReason);
};
}
}
- 3 回答
- 0 关注
- 105 浏览
添加回答
举报