WPF MVVM对话框示例 [英] WPF MVVM dialog example
问题描述
有人有使用MVVM(Prism)显示窗口对话框的示例吗? -例如执行命令时的配置设置窗口.
Does anyone have any examples of showing a window dialog using MVVM (Prism)? - for example a configuration settings window when a command is executed.
我看过的所有示例都使用中介模式,这很好,但是它们都对视图模型中的视图有不理想的引用(我们正在使用DataTemplates)
All of the examples I've seen use the mediator pattern which is fine, but they also all have a reference to the view in the view model which is not ideal (we're using DataTemplates)
谢谢
推荐答案
我将使用服务来显示对话框.然后,该服务还可以将视图链接到视图模型.
I would use a service to display the dialog. The service can then also link views with viewmodels.
public interface IDialogService {
void RegisterView<TView, TViewModel>() where TViewModel:IDialogViewModel;
bool? ShowDialog(IDialogViewModel viewModel);
}
public interface IDialogViewModel {
bool CanClose();
void Close();
}
RegisterView
只是将视图类型与ViewModel类型链接.您可以在模块初始化中设置这些链接.这比尝试让模块在应用程序的顶层注册数据模板要简单得多.
RegisterView
just links the view type with the ViewModel type. You can set up these links in the module initialization. This is simpler than trying to get modules to register datatemplates in the top layer of your application.
ShowDialog
显示要显示的ViewModel.就像Window.ShowDialog
方法一样,它为关闭返回true,false和null.该实现只是从您的容器中创建一个TView
类型的新视图,将其连接到提供的ViewModel上,并显示它.
ShowDialog
Shows the ViewModel you want to display. It returns true, false and null for close just like the Window.ShowDialog
method. The implementation just creates a new view of type TView
from your container, hooks it up to the provided ViewModel, and shows it.
IDialogViewModel
为ViewModel提供了一种验证并取消对话框关闭的机制.
IDialogViewModel
provides a mechanism for the ViewModel to do verification and cancel the closing of the dialog.
我有一个标准的对话框窗口,其中包含内容控件.调用ShowDialog
时,它将创建一个新的标准对话框,将该视图添加到内容控件中,并挂接ViewModel并显示它.标准对话框已经具有[确定]和[取消]按钮,并具有适当的逻辑以从IDialogViewModel
调用正确的方法.
I have a standard dialog window, with a content control in it. When ShowDialog
is called it creates a new standard dialog, adds the view to the content control, hooks up the ViewModel and displays it. The standard dialog already has [OK] and [Cancel] buttons with the appropriate logic to call the right methods from IDialogViewModel
.
这篇关于WPF MVVM对话框示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!