问题描述
我在这个表单上有一个 winform winform1 和 2 个用户控件 control1 和 control2
I have a winform winform1 and 2 user controls control1 and control2 on this form
现在我想定义一个自定义事件,它在 control1 中引发/触发并在 control2 中接收.该事件应该是全局,而不是直接在 control1 中定义.control2 不应该知道 control1 的存在.该事件也应该由其他控件引发.C# 代码如何?我需要发布者类之类的东西吗?
Now I want to define a custom event, which is raised/fired in control1 and received in control2. The event should be global and not directly defined in control1. control2 should not know about the existence of control1. The event should also be raised by other controls. How is the C# code for that? Do I need something like a publisher class?
推荐答案
你描述的看起来像 Mediator模式,其中对象通过消息进行通信.这些消息可以实现为事件、回调或任何其他机制.
What you describe looks like the Mediator pattern, in which objects communicate through messages. These messages can be implemented as events, callbacks, or any other mechanism.
您可以使用 MVVM Light 的 Messenger 类之类的实现(此框架旨在与 WPF 和 Silverlight 一起使用,但您可以获取此特定类的代码并在 WinForms 中使用它)
You could use an implementation like MVVM Light's Messenger class (this framework is intended for use with WPF and Silverlight, but you can get the code for this particular class and use it in WinForms)
// Register for a specific message type
Messenger.Default.Register<TypeOfTheMessage>(this, DoSomething);
...
// Called when someone sends a message of type TypeOfTheMessage
private void DoSomething(TypeOfTheMessage message)
{
// ...
}
// Send a message to all objects registered for this type of message
Messenger.Default.Send(new TypeOfTheMessage(...));
Messenger 类相对于静态事件的一大优势是它使用弱引用,因此它不会阻止订阅对象的垃圾回收,从而降低内存泄漏的风险.
A big advantage of the Messenger class over a static event is that it uses weak references, so it doesn't prevent garbage collection of subscribed objects, which reduces the risk of memory leaks.
请参阅此链接了解有关Messenger 类
这篇关于用 C# 编写全局自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)