Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

alt text

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.

alt text

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top