Thursday, January 9, 2014

[C#] Dialogs the MVVM Way

The Model-View-ViewModel pattern is really nice since it clearly defines the responsibility of the View, the ViewModel and the Model. There should be no direct contact between the View and the ViewModel and via the databinding mechanism, this is easily possible.
 
However, I ran into a problem when a confirmation was required from the user before removing an entity chosen by the user. The command responsible for the removal behavior was triggered from within the View and executed from within the ViewModel. In my opinion, the ViewModel should not directly use any presentation functionality (e.g. showing a MessageBox).
In my quest to find a reasonable solution on the web, I ran into the following solutions:
  1. Just show the messagebox from the ViewModel.  
  2. Use a solution that adds extra code to the View which reacts to a trigger from the ViewModel.
  3. Bind the View to a message property and have it show a messagebox when this changes.
  4. Use one of the available MVVM frameworks and use the solution they provide.
Solution 1 & 2 where directly discarded, solution 3 was getting close however I found it quite limiting to react to a change to a message. Solution 4 was not an option for me since I am not really fond of the MVVM frameworks I reviewed.

Because I was unable to find a solution matching my requirements, I came up with the solution as described in this linked article on CodeProject.