2

When I asked about how to implement a dialog in MVVM someone advised me to read this thread:

MVVM, DialogService and Dialog Result

In the view model, the dialog is called in this way:

var dialog = new DialogViewmodel();
var result = _dialogservice.ShowDialog("My Dialog", dialog);

if(result.HasValue && result.Value)
{
    //accept true
}
else
{
    //Cancel or false
}

But is this different than using a messageBox in this way?

DialogResult result = MessageBox.Show("Hello");

if(result == DialgoResult-OK)
{
    //accept true
}
else
{
    //Cancel or false
}

In this second case, I use MessageBox instead of the custom dialog, so I don't see any difference.

Anyway, in many cases I have read that to use a MessageBox in MVVM application it is a bad idea because it breaks the MVVM pattern. But really if this is true, I don't see how the first solution doesn't break the MVVM pattern and the second one breaks it.

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • Every messagebox is a U/X design error because it interrupts the user. – H H Jul 30 '17 at 07:47
  • But in MVVM and Software Architecture context, try to look at it in terms of dependencies and testability. A VM that calls MessagBox directly is much harder to test. – H H Jul 30 '17 at 07:49
  • Why not just create an `IAlertService` to handle `MessageBox`s in exactly the same way you did for dialogs? –  Jul 30 '17 at 08:14
  • Does this answer your question? [How have you successfully implemented MessageBox.Show() functionality in MVVM?](https://stackoverflow.com/questions/1098023/how-have-you-successfully-implemented-messagebox-show-functionality-in-mvvm) – StayOnTarget Apr 22 '20 at 20:54

1 Answers1

4

The basic idea of the MVVM pattern is the separation of concerns. The View Model should not know how to handle or present a dialog. Why? Here are some reasons:

  • Testing your View Model: No dialogs are desired (Imagine you need to click dialogs all the time)
  • Creating a console application of a GUI application (The dialogs should be shown in console not as popup boxes)
  • It is required to change the design of your dialogs (Imagine you need to change all MessageBox calls)
  • ...

Solution: Using dependency injection by implementing a well defined interface for dialogs. You can find a very good and basic example in in this answer.

Result: Calling _dialogservice.ShowDialog is maybe only a wrapper of MessageBox.Show but could also be a some dialog in a console in a console application or debug log during testing. So the code is well separated of any presentation.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49