¿Cómo debo generar cuadros de diálogo desde mis ViewModels?

Is there any kind of consensus about best practices for dialog windows in MVVM (for WPF)? I've seen it approached via two ways:

  1. A mediator (EventAggregator, EventBus, or whatever you like to call it) that sends a "RequestsDialog" message and waits for a "DialogProcessed" message.

  2. A dialog declared in the view xaml itself which is bound to the caller's view model and shown via a Command or EventTrigger or something like that.

I'm trying to figure out which is a better way to go, and I need some help.

My concern with #1 is (and always has been), what's the best way of controlling the scope of the request and reply messages? I mean, let's say I have both "local" messages and "global" application messages being processed by my mediator....how do I make sure my ViewModel can still receive global messages...but at the same time that another ViewModel on the current window doesn't accidentally receive the DialogProcessed message intended for the active ViewModel.

Take the following scenario:

  • Ventana 1
  • 2 UserControls, each bound to independent ViewModels
  • ViewModel1 sends a RequestConfirmation message and waits for a ConfirmationResponse message
  • I also have global messages to receive in ViewModel1 (like a RequestCloseWindow message).

How do I prevent ViewModel2 from getting the ConfirmationResponse message for the RequestConfirmation message initiated by ViewModel1?

preguntado el 08 de noviembre de 11 a las 15:11

2 Respuestas

You can either pass a parameter along with the message which identifies who it is for, or have the Message include a delegate of some method to execute once its finished.

Usually I prefer to use an identifier because it's simpler. Sometimes it's an Id or GUID, but usually it's just this. That way in the method that handles the Processed messages I can just say

if (evt.Source != this) return;

respondido 08 nov., 11:20

And the guy that fires the "Response" event in passes the original source from the "Request" event in the response's evt.Source? - Jeff

@JeffN825 Sure, that's one way to do it - Rachel

Did you try using something similar to InteractionRequests from Prism ?

They are exactly covering scenario you've described. Take a look at este artículo.

respondido 08 nov., 11:20

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.