How should I create dialog boxes from my ViewModels?

Is there any consensus regarding best practices for dialog boxes in MVVM (for WPF)? I saw him approaching in two ways:

  • An intermediary (EventAggregator, EventBus, or whatever you like to call) that sends a "RequestsDialog" message and waits for a "DialogProcessed" message.

  • A dialog declared in the xaml view itself, which is tied to the caller's view model and displayed via Command or EventTrigger or something like that.

I am trying to figure out which way is better and I need help.

My problem is C # 1 (and always has been), what's the best way to control the amount of request and response messages? I mean, say, I have both β€œlocal” messages and β€œglobal” application messages processed by my intermediary .... how can I make sure that my ViewModel can still receive global messages ... but in the same time that another ViewModel in the current window does not accidentally receive a DialogProcessed message intended for the active ViewModel.

Run the following script:

  • 1 Window
  • 2 UserControls, each of which is tied to independent ViewModels
  • ViewModel1 sends a RequestConfirmation message and waits for a ConfirmationResponse message
  • I also have global messages to receive in ViewModel1 (e.g. RequestCloseWindow message).

How to prevent ViewModel2 from receiving a ConfirmationResponse message for a RequestConfirmation message initiated by ViewModel1?

+4
source share
2 answers

Have you tried using something similar to Prism's InteractionRequests?

They accurately describe the scenario you described. Take a look at this article.

+1
source

You can either pass a parameter along with a message that identifies who it is intended for, or send a message to a delegate of some method to execute after it completes.

I usually prefer to use an identifier because it is simpler. Sometimes it's an Id or GUID, but usually it's just this . Thus, in the method that processes Processed messages, I can simply say

 if (evt.Source != this) return; 
+1
source

Source: https://habr.com/ru/post/1380220/


All Articles