在C#中编写全局自定义事件 [英] Writing a global custom event in C#

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

问题描述

我在此表单上有一个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?

推荐答案

你所描述的内容看起来像中介模式,其中对象通过消息进行通信。这些消息可以被实现为事件,回调或任何其他机制。

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 class

See this link for details about the Messenger class

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

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