WPF MVVM模式下打开子窗口的该实现方案是否符合规范?
WPF MVVM模式下无第三方依赖弹窗方案合规性判断
方案背景与设计要求
我耗时一个月研究如何在不违反MVVM规则的前提下,于WPF MVVM模式中打开新窗口,查阅了社区内几乎所有相关帖子与教学视频,但作为业余开发者始终未找到易于理解的实现方案。
最终我结合查阅到的资料整理出一套实现方案,方案需满足以下要求:
- 友好支持依赖注入
- 不违反MVVM模式规则
- 可复用于多个视图场景
- 使用简便,无需为每个窗口编写上百行冗余代码
- 不引入DialogMVVM等第三方专用库(本人处于学习阶段,希望完全理解自身编写代码的运行逻辑)
说明:当前业务场景无需获取对话框返回结果,因此方案未包含该部分功能。
具体实现步骤
- 基于DataTemplate编写DialogWindow通用容器模板
<Window x:Class="AWH.Views.DialogWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodels="clr-namespace:AWH.ViewModels" xmlns:views="clr-namespace:AWH.Views" mc:Ignorable="d" SizeToContent="WidthAndHeight"> <Window.Resources> <DataTemplate DataType="{x:Type viewmodels:ProductAddViewModel}"> <views:ProductView/> </DataTemplate> </Window.Resources> </Window>
- 定义IDialogService服务接口及DialogService实现类
public interface IDialogService { void ShowDialog(object viewModel); } public class DialogService : IDialogService { public void ShowDialog(object viewModel) { var win = new DialogWindow(); win.Content = viewModel; win.ShowDialog(); } }
- 在业务ViewModel(本示例为ProductListViewModel)中实现窗口打开触发逻辑
public class ProductListViewModel : ViewModelBase { private IDialogService _dialogService; private IProductAddViewModel _productAddViewModel; public ICommand AddProductCommand { get; set; } public ProductListViewModel(IDialogService dialogService, IProductAddViewModel productAddViewModel) { _productAddViewModel = productAddViewModel; _dialogService = dialogService; AddProductCommand = new DelegateCommand(OpenAddProductDialog); } private void OpenAddProductDialog() { _dialogService.ShowDialog(_productAddViewModel); } }
- 在App.xaml.cs中完成依赖注入配置(基于IServiceCollection实现)
services.AddSingleton<ProductListViewModel>(); services.AddSingleton<IProductAddViewModel, ProductAddViewModel>(); services.AddSingleton<IDialogService, DialogService>();
核心疑问
以上就是方案全部内容。我认为该方案未违反MVVM模式:ViewModel未直接调用视图,仅传递ViewModel实例,剩余视图匹配逻辑由WPF通过DataTemplate自动完成,请问该判断是否正确?
补充说明:触发打开操作的命令需要绑定到对应视图控件上,本示例中与ProductListViewModel关联的ProductListView.xaml内,触发按钮的绑定代码如下:
<Button Content="Add product" Margin="10 15" Padding="8 5" VerticalAlignment="Stretch" Command="{Binding AddProductCommand}" />
内容的提问来源于stack exchange,提问作者Świętopeł Ziemowit
相关产品推荐
相关产品推荐

