简体   繁体   English

如何在MVVM中实现对话框架构

[英]How to implement dialog architecture in MVVM

I am developing a WPF 4.0 - MVVM application based on PRISM framework (Unity Container). 我正在开发基于PRISM框架(Unity Container)的WPF 4.0-MVVM应用程序。

I was wondering what is the best way to implement dialogs in the mvvm pattern. 我想知道在mvvm模式中实现对话框的最佳方法是什么。 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. 我让ViewModel在需要获取用户信息时引发事件。 It is then up to the View how to supply it. 然后由View查看如何提供它。 This does mean that the code behind file will get Event handlers though, something real MVVM adepts will shudder at... 确实意味着文件背后的代码将获得事件处理程序,真正的MVVM专家将会不寒而栗......

Since you are using Prism/Unity implement the mediator pattern for your View Models. 由于您使用的是Prism / Unity,因此请为View Models实现中介模式。

  1. Add a DialogService (IDialogService) module to your project. 将DialogService(IDialogService)模块添加到项目中。
  2. Modules containing dialogs register them with the IDialogService. 包含对话框的模块使用IDialogService注册它们。 Don't forget to declare DialogServiceModule as a ModuleDependency. 不要忘记将DialogServiceModule声明为ModuleDependency。
  3. ViewModels now use the IDialogService to show the required dialog. ViewModels现在使用IDialogService来显示所需的对话框。

     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. 如果在View中使用ViewModel事件和处理程序,请使用WeakEventHandler模​​式来消除潜在的资源泄漏。 Also, it is possible for multiple Views to be attached to the same ViewModel. 此外,可以将多个视图附加到同一ViewModel。 I've worked on projects with one ViewModel -> one View. 我使用一个ViewModel工作项目 - >一个View。 But also one ViewModel -> multiple Views. 而且还有一个ViewModel - >多个视图。 Just something to consider when making your design decisions. 在做出设计决策时需要考虑的事项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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