Creating an MVVM friendly dialog strategy

When designing a UI with MVVM the goal is to separate the concerns of the View from the concerns of the ViewModel. Ideally, the ViewModel should not rely on any view components. However, this is the idal and another rule of MVVM is that you should design your application as you wish.

In the area providing a service showing dialogs there are two different approaches floating arround:

  1. Implementing the DialogService on the View (e.g. see http://geekswithblogs.net/lbugnion/archive/2011/04/13/deep-dive-mvvm-samples-mix11-deepdivemvvm.aspx Sample 03).
  2. Implementing a service component that does is not attached to the view (e.g. see http://blog.roboblob.com/2010/01/19/modal-dialogs-with-mvvm-and-silverlight-4/)

Both approaches rely on an interface that defines the functionality the service provides. The implementation for this Service is then injected into the ViewModel.

Also, do both approaches have their specific advantages and disadvantages.

  • The first approach works also well for WP7, however, it requires a common view base class as this contains the implementation of the view service.
  • The second approach works well for SilverLight and WPF and appleals as it keeps the service separate from the view and does not impose any restictions on the view.

Another possible solution is to use messaging to show the dialogs.

Whatever approach you are using try to keep the View and the ViewModel de-coupled by using an IoC (inversion of control) pattern, i.e. define an interface so that you can use different implementations. To bind the services into the ViewModel use injection, i.e. passing the service into the constructor of the ViewModel or by setting a property.

Leave a Comment