用 C# 编写全局自定义事件

Writing a global custom event in C#(用 C# 编写全局自定义事件)

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

问题描述

我在这个表单上有一个 winform winform1 和 2 个用户控件 control1control2

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# 编写全局自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:用 C# 编写全局自定义事件

基础教程推荐