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

标签 c# .net winforms events delegates

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

现在我想定义一个自定义事件,它在 control1 中引发/触发并在 control2 中接收。该事件应该是全局的,而不是直接在 control1 中定义。 control2 不应该知道 control1 的存在。 该事件也应由其他控件引发。 C# 代码如何?我需要发布者类之类的东西吗?

最佳答案

你描述的看起来像Mediator pattern ,其中对象通过消息进行通信。这些消息可以作为事件、回调或任何其他机制来实现。

您可以使用类似 MVVM Light 的实现的 Messenger 类(此框架旨在与 WPF 和 Silverlight 一起使用,但您可以获得此特定类的代码并在 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 类相对于静态事件的一大优势是它使用弱引用,因此它不会阻止订阅对象的垃圾回收,从而降低内存泄漏的风险。

参见 this link有关 Messenger 类的详细信息

关于c# - 用 C# 编写全局自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475723/

相关文章:

c# - 是否可以将数据从 C# 应用程序发送到网站/网络服务器?

C# 浏览器缩放

c# - 使用定界符拆分字符串,但在 C# 中保留结果中的定界符

c# - 什么时候用 IList 什么时候用 List

c# - 调试 IEnumerable 方法

c# - Winforms 中禁用的菜单项仍然显示子项

C#:你会将字符串转换/翻译功能放在哪里?

c# - Visual Studio 中的 LINQPad

.net - 是否有类似的命令,如 .call for .NET?

c# - 根据参数,以编程方式启动 CLI 应用程序不起作用