Omri Btian Omri Btian - 3 months ago 44
C# Question

How to implement dialog architecture in MVVM

I am developing a WPF 4.0 - MVVM application based on PRISM framework (Unity Container).

I was wondering what is the best way to implement dialogs in the mvvm pattern.
I am planning to use quite a few in my application so I want something reusable.


Since you are using Prism/Unity implement the mediator pattern for your View Models.

  1. Add a DialogService (IDialogService) module to your project.
  2. Modules containing dialogs register them with the IDialogService. Don't forget to declare DialogServiceModule as a ModuleDependency.
  3. ViewModels now use the IDialogService to show the required dialog.

    public interface IDialogService
        void    RegisterDialog  (string dialogID, Type type);
        bool?   ShowDialog      (string dialogID);
    public class DialogService : IDialogService
        private IUnityContainer       m_unityContainer;
        private DialogServiceRegistry m_dialogServiceRegistry;
        public DialogService(IUnityContainer unityContainer)
            m_unityContainer = unityContainer;
            m_dialogServiceRegistry = new DialogServiceRegistry();
        public void RegisterDialog(string dialogID, Type type)
            m_dialogServiceRegistry.RegisterDialog(dialogID, type);
        public bool? ShowDialog(string dialogID)
            Type type = m_dialogServiceRegistry[dialogID];
            Window window  = m_unityContainer.Resolve(type) as Window;
            bool? dialogResult = window.ShowDialog();
            return dialogResult;

If you use ViewModel events & handlers in the View, use the WeakEventHandler pattern to eliminate a potential resource leak. Also, it is possible for multiple Views to be attached to the same ViewModel. I've worked on projects with one ViewModel -> one View. But also one ViewModel -> multiple Views. Just something to consider when making your design decisions.