简体   繁体   English

实施WPF MVVM对话框服务

[英]Implementing WPF MVVM Dialog Service

I'm trying to implement the "MVVM recommended" way of handling multiple views/windows in the application thru a DialogService. 我正在尝试通过DialogService在应用程序中实现处理多个视图/窗口的“推荐的MVVM”方法。 However, I encountered a difficulty in implementing closing the parent view after showing the child view. 但是,在显示子视图之后,在实现关闭父视图时遇到了困难。 Here's my implementation so far. 到目前为止,这是我的实现。 What is the best strategy for WPF MVVM to handle such scenario? WPF MVVM处理这种情况的最佳策略是什么?

DialogService.cs (I try to make this generic so that it can show and close any windows) DialogService.cs(我尝试使其通用,以便它可以显示和关闭任何窗口)

public class DialogService : IDialogService
{
    /// <summary>
    /// Closes the specified window screen
    /// </summary>
    /// <param name="dialogWindow"></param>
    public void CloseDialog(Window dialogWindow)
    {
        if ( dialogWindow != null )
            dialogWindow.Close ( );       
    }

    /// <summary>
    /// Shows the specified window screen
    /// </summary>
    /// <param name="dialogWindow"></param>
    public void ShowDialog(Window dialogWindow)
    {
        if ( dialogWindow != null )
            dialogWindow.ShowDialog ( );
    }
}

The view model that shows the child view is SelectPackageViewModel.cs 显示子视图的视图模型是SelectPackageViewModel.cs

public SelectPackageViewModel(IPackageDataService packageDataService, IDialogService dialogService)
{
    this.packageDataService = packageDataService;
    this.dialogService = dialogService;
    LoadPackages();
    LoadCommands();
}
private void LoadCommands()
{
    CreateNewCommand = new CustomCommand(CreateNewPackage);
}
private void CreateNewPackage(object obj)
{            
    dialogService.ShowDialog(new CreatePackage());            
}

The parent view SelectPackage.cs. 父视图SelectPackage.cs。 The child view is CreatePackage.cs 子视图是CreatePackage.cs

<Button Name="btnNewPackage"
    Content="New..."
    HorizontalAlignment="Center"
    Width="120"
    Height="30"
    FontSize="15" FontWeight="Bold"
    Margin="10"
    Command="{Binding CreateNewCommand}"/>

You can always use the NuGet package called MvvmDialogs, or look at its implementation. 您始终可以使用称为MvvmDialogs的NuGet包,或查看其实现。 After all It's open source on GitHub. 毕竟,它在GitHub上是开源的。

Friendly advice, be aware of answers regarding MVVM that are absolute. 友善的建议,请注意关于MVVM的绝对答案。 These answers often come from developers in the learning phase, where rules and guidelines are followed without understanding their benefit. 这些答案通常来自学习阶段的开发人员,在该阶段遵循规则和准则,却不了解其好处。 As you progress you start to question "why", and become more pragmatic. 随着您的进步,您开始质疑“为什么”,并且变得更加务实。 The idea that the view model shouldn't be aware of a view service is just silly. 视图模型不应该知道视图服务的想法是愚蠢的。 It is a view model, the view is in it's name. 这是一个视图模型,视图就是它的名字。

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

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