写在C#中一个全球性的自定义事件 [英] Writing a global custom event in C#

查看:145
本文介绍了写在C#中一个全球性的自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WinForm的 winform1 和2的用户控件控制1 控制2 在这种形式

I have a winform winform1 and 2 user controls control1 and control2 on this form

现在我要定义一个自定义事件,这是引发/发射的控制1和控制2接收。该事件应该是全球并没有控制1直接定义。控制2不应该知道CONTROL1的存在。 该事件也应由其他控件提高。如何在C#code是什么?我是否需要像一个出版商类?

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?

推荐答案

你描述看起来像调解模式是什么,在哪些对象通过消息进行通信。这些消息可以被实现为事件,回调,或任何其它机构。

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光使者<实施/ code>类(该框架旨在与WPF和Silverlight的使用,但你可以得到code这个特殊类,并使用它的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(...));

使者类通过静态事件的一大优点是,它使用弱引用,所以它确实认购对象不是prevent垃圾收集,这降低了内存泄漏的风险。

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.

请参阅此链接有关使者类的详细信息

See this link for details about the Messenger class

这篇关于写在C#中一个全球性的自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆