消息(不是例外)应该如何从模型/业务对象层传递到 UI?
使用 VB.net 4.0,
我有一个松散地基于 MVVM 的 Winforms 应用程序。我正在寻找一种简单的方法,让任何层(甚至是 UI 没有引用的层)将消息传递回 UI 以显示给用户。
我过去通过在每个其他程序集都会引用的“公共”程序集中创建一个“Communicator”类来实现此目的。
Public Class Communicator
Public Shared Sub NotifyUser(Message as string)
RaiseEvent SendMessage(Message)
End Sub
Public Shared Event SendMessage(MessageToSend as string)
End Class
UI 将在程序启动时订阅 SendMessage 事件。任何想要向用户传递消息的类都只需调用 Shared NotifyUser 方法,而 Communicator 类将通过 SendMessage 事件将给定消息中继到 UI。
这种方法的优点是实现起来很简单,并且在代码中的任何地方都非常容易使用。
我认为这样做的缺点是对 NotifyUser 的调用分布在整个代码中,使得许多类依赖于 Communicator 类及其共享方法。出于某种原因,感觉不对。
所以,我的问题是,在不显着增加复杂性的情况下实现相同效果的一些典型方法是什么?
Using VB.net 4.0
I have a Winforms application that is loosely based on MVVM. I'm looking for an easy way for any layer (even those that the UI has no reference to) to pass messages back to the UI for display to the user.
I have accomplished this in the past by creating a "Communicator" class in a "Common" assembly that every other assembly would reference.
Public Class Communicator
Public Shared Sub NotifyUser(Message as string)
RaiseEvent SendMessage(Message)
End Sub
Public Shared Event SendMessage(MessageToSend as string)
End Class
The UI would subscribe to the SendMessage event at program startup. Any class wanting to pass a message to the user would simply call the Shared NotifyUser method and the Communicator class would relay the given message to the UI through the SendMessage event.
The upside to this method is that it is trivial to implement and super easy to use from anywhere in your code.
I suppose the downside to this is that calls to NotifyUser are spread throughout your code, making many classes dependent on the Communicator class and its shared method. For some reason, it just feels wrong.
So, my question is, what are some typical ways to achieve the same effect without a significant increase in complexity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
老实说,活动很好(有你指出的缺点)。另一种选择是中介模式,这或多或少听起来像你已经实施,只是没有事件。
Honestly events are fine (with the downsides you pointed out). Another option is the Mediator pattern, which is more or less what it sounds like you've implemented, just without events.