WPF MVVM 对话框示例 [英] WPF MVVM dialog example

查看:27
本文介绍了WPF MVVM 对话框示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人有使用 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 并显示它.标准对话框已经有 [OK] 和 [Cancel] 按钮,带有适当的逻辑来从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆