Omri Btian
Omri Btian

Reputation: 6547

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.

Upvotes: 7

Views: 3817

Answers (2)

Steven Licht
Steven Licht

Reputation: 770

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.

Upvotes: 2

Dabblernl
Dabblernl

Reputation: 16101

I let the ViewModel raise events when it needs to get user information. It is then up to the View how to supply it. This does mean that the code behind file will get Event handlers though, something real MVVM adepts will shudder at...

Upvotes: 1

Related Questions