Wednesday, June 24, 2015

User Interactions in MVVM - Overview

One of the common questions regarding MVVM is, how to interact with the user. For example: how to present the user a message, how to open a window and the like.

Many programmers come to this point, and they are giving up the principles of MVVM. Sometimes, they ask: Why not open a MessageBox from the ViewModel? Why do we need beating about the bush,but not to write the code simple and short MessageBox.Show ("Some message")?

With Dialogs the problem is more complicated. Without MVVM, we would write code like this:

var dialogViewModel = new dialogViewModel();
var dialogView = new dialogView()
{
    DataContext = dialogViewModel
};
dialogView.Show();

But according to the principles of MVVM, the ViewModel is forbidden to be aware to MyDialogView, so what will he do with MyDialogViewModel? And what actually forbidden to be aware ViewModel to View? And in this regard, many people wonder: Why not write the simple code above?

So first, Let's mention one of the goals of MVVM: Testability. See here for more info about this point: Writing a Testable Presentation Layer with MVVM

That is why in ViewModel should not write something like MessageBox.Show or MyView.Show, because it blocks the possibility of writing tests.

So what to do? An exhaustive description of the solutions, you can read in this recommended article: User interactions patterns writen by Prism team.

But i think that Prism's paradigm is too complicated. If you have 100 MessageBox'es, you should create 100 InteractionRequest's and 100 InteractionRequestTrigger and they are all doing exactly the same work, so why duplicate the code again and again?!

And on the sidewalk across the street, if we are looking on MVVMLight - The other common library, it's doesn't includes any solution for interactivity. It's include only IDialogService interface, but not any implementation of this interface.

In the coming posts, we will implement simple and convenient patterns for interactions, alert, prompt, popups and more.

No comments:

Post a Comment