简体   繁体   中英

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.

这篇关于MVVM对话的文章你可能会觉得很有用: http//www.codeproject.com/Articles/36745/Showing-Dialogs-When-Using-the-MVVM-Pattern

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM