我正在开发一个新的 WPF 应用程序,并且我正在尝试尽可能接近 MVVM 模式。我的 XAML 文件现在没有代码隐藏,我的所有交互性都是使用 Josh Smith 的 RelayCommand 类和 ViewModel 类中的命令来实现的。
在我开始处理内务任务(例如“关于”框和系统首选项页面)之前,这种方法非常有效。我希望将这些作为模式对话框,但如果我创建一个 RelayCommand 来打开这些页面,我将在视图模型中创建对视图的依赖项。
这让我觉得与 MVVM 模式的本质背道而驰。
是否有一种既定方法可以在 MVVM 模式中创建新窗口(模式和/或非模式)而无需创建依赖项?似乎保持 ViewModel 干净的唯一方法是在 XAML 代码隐藏文件中创建 Click 事件处理程序,并在旧视图中创建新视图。
有什么建议吗?
I'm working on a new WPF application and I'm trying to stay as close to the MVVM pattern as I can. My XAML files right now have no codebehinds, and all my interactivity is achieved using Josh Smith's RelayCommand class and commands in my ViewModel classes.
This worked great until I started working on the housekeeping tasks, such as an about box and a system preferences page. I want to have these as modal dialogs, but if I create a RelayCommand to open these pages, I'll be creating a dependency on the view within my view model.
This strikes me as against the grain of the MVVM pattern.
Is there an established method for creating new windows (modal and/or modeless) within the MVVM pattern without creating a dependency? It seems the only way I can keep the ViewModel clean is to create a Click event handler in the XAML codebehind file and create the new view within the old view.
Any recommendations?
发布评论
评论(5)
处理此问题的一种方法是实现向 ViewModel 提供视图的服务。视图向服务注册,ViewModel 可以向服务请求对话框。这是四人帮调解者模式的示例。
One way to handle this is to implement a service that provides Views to ViewModels. Views register with the service and ViewModels can request dialogs from the service. This is an example of the Gang of Four mediator pattern.
看一下我的 Silverlight 4 模态对话框解决方案:
使用 MVVM 和 Silverlight 4 的模态对话框
Take a look at my Modal Dialogs solution for Silverlight 4:
Modal dialogs with MVVM and Silverlight 4
请参阅我对这个问题的回答,了解为什么 Window 类本身是ViewModel,因此您可以直接从 ViewModel 使用它,无需担心。
Please see my answer to this question about why the Window class itself is a ViewModel, so you can use it directly from your ViewModel without worries.
Laurent Bugnion 有一个弱引用中介器,他用它来显示对话消息。与广播的消息一起,还会发送回调委托以供订阅者执行。您可以使用相同的概念来显示“关于”对话框。查看 DialogMessage.cs 来自此处的源代码。
Laurent Bugnion has a weak-referenced mediator, in which he uses it to show dialog messages. Along with the message that is broadcast, a callback delegate is sent for the subscriber to execute. You could use the same concept to show an about dialog. Check out DialogMessage.cs from the source here.
我们使用负责 UI 工作流程的控制器类。他们创建模态窗口并在各种 ViewModel 之间进行协调。
ViewModel 示例应用程序显示了如何使用 View-Model-ViewModel (MVVM) 模式打开模态窗口:
WPF 应用程序框架 (WAF)
http://waf.codeplex.com
We use Controller classes which are responsible for the UI Workflow. They create the modal windows and they mediate between various ViewModels.
How you can open a modal window with the View-Model-ViewModel (MVVM) pattern is shown in the ViewModel sample application here:
WPF Application Framework (WAF)
http://waf.codeplex.com