Using MVVM Foundation Messenger to Show Dialog

不问归期 提交于 2019-12-12 09:41:23

问题


I'm building a WPF app and trying to conform to MVVM best practices. I'm using the MVVM Foundation framework and noticed the Messenger class, which I've read should be used for handling dialogs in WPF. This sounds great, but I'm totally not understanding how to use a Messenger for this purpose. Literally, all I want to do is open a modal About dialog --I don't need to pass any messages back and forth.

Was the intent of the Messenger class to be used for cases where dialogs require a message from its parent, or return a message to its parent? Is it overkill for an About dialog? Would I be better off simply adding code to an event handler to show the dialog?


回答1:


The idea behind the messaging pattern doesn't specifically have anything to do with showing dialogs. The idea is simply to provide a decoupled way to communicate between ViewModels.

You can leverage this infrastructure to solve your problem but you will have to implement the showing of the dialog yourself.

As Phillip showed above you can send messages between ViewModels. When your ViewModel receives the message it can set it's own internal property, say "ShowDialog", to true.

You can then have a binding that reacts to this property change operation and opens a dialog.

I have also built a simple messaging framework for the MVVM pattern that borrows from Josh's idea (and several other existing frameworks) you can read about it here




回答2:


Say you have a parent view and a dialog view. In MVVM they would both have a view model. It is good to keep these view models decoupled, i.e. they don't have references to each other. And yet they need to communicate to each other. The Messenger class acts as a go between or Mediator to mediate the communication of information between the two classes. See the code taken from Josh's blog.

Here is Object A. It's call to the mediator's Register method implements: when I receive the message ObjectBSaidSomething, from the mediator, I'll cache it in the member WhatObjectBSays.

Here is Object B, which implements: I'm going to send a message ObjectBSaidSomething. Note, that Object B knows nothing about Object A. There might be nothing listening for ObjectBSaidSomething, or 100 objects listening for ObjectBSaidSomething, but Object B doesn't know and doesn't care. This is good decoupling, and this is why the Mediator pattern is a good idea. And this is the way the MVVM foundation is recommending that information is passed between view models.



来源:https://stackoverflow.com/questions/1792814/using-mvvm-foundation-messenger-to-show-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!