WPF 中的 Prism 弹出新 window

Prism pop-up new window in WPF

如何在 WPF 中 open/close 一个新的 window 而不违反 MVVM 模式的规则?
我只是想模仿 ms office outlook 的登录模块。

我已经阅读了this article,但是传递参数时出错confirmation

我目前使用的是 prism 5.0。

幸运的是,Prism 5.0(我假设也是 6.0,还没有使用它)有一个名为 InteractionRequest<T> 的 class,您可以从代码中使用它来提出交互请求。

交互请求基本上是一个 window,要求用户执行特定操作并与用户一起调用回调(如果需要或需要)decisions/actions。

public class ShellViewModel : BindableBase
{
    private readonly IRegionManager regionManager;

    public ShellViewModel(IRegionManager regionManager)
    {
        if (regionManager == null)
            throw new ArgumentNullException("regionManager");

        this.regionManager = regionManager;
        this.OptionSettingConfirmationRequest = new InteractionRequest<IConfirmation>();

        openConnectionOptionsCommand = new DelegateCommand(RaiseConnectionOptionsRequest);
    }

    public InteractionRequest<IConfirmation> OptionSettingConfirmationRequest { get; private set; }

    private readonly ICommand openConnectionOptionsCommand;
    public ICommand OpenConnectionOptionsCommand { get { return openConnectionOptionsCommand; } }

    private void RaiseConnectionOptionsRequest()
    {
        this.OptionSettingConfirmationRequest.Raise(new Confirmation { Title = "Options not saved. Do you wish to save?" }, OnConnectionOptionsResponse);
    }

    protected virtual void OnConnectionOptionsResponse(IConfirmation context)
    {
        if(context.Confirmed)
        {
            // save it
        }

        // otherwise do nothing
    }
}

在XAML中你会做类似

的事情
<Button Content="Options" Command="{Binding OpenConnectionOptionsCommand}">
    <i:Interaction.Triggers>
        <pit:InteractionRequestTrigger SourceObject="{Binding OptionSettingConfirmationRequest, Mode=OneWay}" >
            <pie:LazyPopupWindowAction RegionName="ConnectionSettings" 
                                NavigationUri="ConnectionSettingsView" IsModal="True" />
        </pit:InteractionRequestTrigger>
    </i:Interaction.Triggers>
</Button>

我使用了我自己的 PopupWindowAction 实现(请参阅 github 项目页面了解其实现),称为 LazyPopupWindowAction,它将在单击时实例化嵌入式 ConnectionSettingsView 视图。如果您不关心您的视图只被实例化一次,请随意使用 PopupWindowAction,那么它将与包含操作的视图同时被实例化。

它基本上是通过从我的一个项目中删除一些无用的行来复制和粘贴。我使用 IConfirmationINotification 接口而不是具体实现。

XAML 与 PopupWindowAction

<Button Content="Options" Command="{Binding OpenConnectionOptionsCommand}">
    <i:Interaction.Triggers>
        <pit:InteractionRequestTrigger SourceObject="{Binding OptionSettingConfirmationRequest, Mode=OneWay}" >
            <pi:PopupWindowAction>
                <pi:PopupWindowAction.WindowContent>
                    <views:CustomPopupView />
                </pi:PopupWindowAction.WindowContent>
            </pi:PopupWindowAction>
        </pit:InteractionRequestTrigger>
    </i:Interaction.Triggers>
</Button>

命名空间声明

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:pi="clr-namespace:Microsoft.Practices.Prism.Interactivity;assembly=Microsoft.Practices.Prism.Interactivity"
xmlns:pit="clr-namespace:Microsoft.Practices.Prism.Interactivity.InteractionRequest;assembly=Microsoft.Practices.Prism.Interactivity"
xmlns:pie="clr-namespace:MyProject.UI.Prism.Interactivity;assembly=MyProject.UI"

更新: 由于人们不断询问 LazyPopupWindowAction,我将源代码放在 GitHub Gist 中。基本上它基于 Prims 5 的 PopupWindowAction(对于 Prism,还没有用 Prism 6 测试它,可能无法进行 w/o 调整)并做完全相同的事情,但也增加了打开的区域和导航支持 window,这是我在应用程序中需要的东西。

我不喜欢默认实现的一件事是,视图和它的视图模型将在 Shell 被实例化的同时被实例化,并且 ViewModel 保持在它的状态,当你关闭它时(它实际上只是隐藏了)。

你用Prism 7吗?
如果是,那么现在停止阅读并转到
如果否,则继续阅读


更新
导致我提出另一个答案的原因是无法在我的项目 中应用已接受的答案,该项目使用 Prism 6
但在给出原始答案之后(见下文)并在评论中讨论它,我发现核心问题是: Prism 6 更改了一些 classes 的名称空间,所有 classes 中使用的已接受的答案仍然存在于 Prism 6 中,但存在于另一个 dll 和命名空间中
因此,如果您使用的是 Prism 6,您可以应用已接受的答案并进行这些修改

首先替换那些命名空间

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:pi="clr-namespace:Microsoft.Practices.Prism.Interactivity;assembly=Microsoft.Practices.Prism.Interactivity"
xmlns:pit="clr-namespace:Microsoft.Practices.Prism.Interactivity.InteractionRequest;assembly=Microsoft.Practices.Prism.Interactivity"

具有以下命名空间

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:prism="http://prismlibrary.com/"

第二次更新XAML如下

<Button Content="Options" Command="{Binding OpenConnectionOptionsCommand}">
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding OptionSettingConfirmationRequest, Mode=OneWay}" >
            <prism:PopupWindowAction>
                <prism:PopupWindowAction.WindowContent>
                    <views:CustomPopupView />
                </prism:PopupWindowAction.WindowContent>
            </prism:PopupWindowAction>
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>
</Button>

注 1
确保您正在使用的视图(在上面的示例中 <views:CustomPopupWindow>)不是 window,否则您将收到异常。

注 2
如果您使用的是 Prism 6,则 ONLY 需要这些修改。因为(正如我在下面的原始答案中所说)接受的答案使用的 dll 是 弃用 在棱镜 6 中。

注 3
确保您引用的是 Prism.Wpf dll,它可能是 downloaded from Nuget.


原始答案
已接受的答案指向Prism 5,它使用this library,即Prism 6.

中已弃用

实际上 the article which you reference 你的问题非常有帮助(至少对我来说),而且它不会崩溃。

我会尽量总结那篇文章。

ViewModel

public class ViewModel : BindableBase
{
    public ViewModel()
    {
        _showWindowCommand = new DelegateCommand(ShowWindow);
        _interactionRequest = new InteractionRequest<Confirmation>();
    }

    private readonly DelegateCommand _showWindowCommand;
    private InteractionRequest<Confirmation> _interactionRequest;

    public ICommand ShowWindowCommand
    {
        get { return _showWindowCommand; }
    }

    public IInteractionRequest InteractionRequest
    {
        get { return _interactionRequest; }
    }

    private void ShowWindow()
    {
        _interactionRequest.Raise(
            new Confirmation(),
            OnWindowClosed);
    }

    private void OnWindowClosed(Confirmation confirmation)
    {
        if (confirmation.Confirmed)
        {
            //perform the confirmed action...
        }
        else
        {

        }
    }
}

XAML

<Button Command="{Binding ShowWindowCommand}" Content="Show Window" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Raised" SourceObject="{Binding InteractionRequest}">
            <i:EventTrigger.Actions>
                <local:ShowWindowAction></local:ShowWindowAction>
            </i:EventTrigger.Actions>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

并且您将需要使用这些命名空间

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:The namespace which contains the ShowWindowAction">

ActionTrigger

using System;
using Prism.Interactivity.InteractionRequest;
using System.Windows.Interactivity;
using System.Windows;

public class ShowWindowAction : TriggerAction<FrameworkElement>
{
    protected override void Invoke(object parameter)
    {
        InteractionRequestedEventArgs args = parameter as InteractionRequestedEventArgs;
        if (args != null)
        {
            Confirmation confirmation = args.Context as Confirmation;
            if (confirmation != null)
            {
                // Replace ParametersWindow with your own window.
                ParametersWindow window = new ParametersWindow();
                EventHandler closeHandler = null;
                closeHandler = (sender, e) =>
                {
                    window.Closed -= closeHandler;
                    args.Callback();
                };
                window.Closed += closeHandler;
                window.Show();
            }
        }
    }
}

说明

  1. 您需要 Prism.CorePrism.Wpf dll(至少)才能使此代码正常工作。
  2. ShowWindow方法,会触发ShowWindowActionInvoke方法,真正显示window.
  3. 您可以处理 OnWindowClosed 中 window 的关闭,我们将其作为回调传递给 ShowWindowAction class,我们从window 真的关门了。

此答案仅适用于 Prism 7,
如果您使用以前版本的 Prism(6 及以下版本)
则此答案不适合您

Prism 7 彻底改变了打开新 windows 的方式。
如果你想阅读,这里是 offical documentation

这里还有一个 Youtube video 解释了 Prism 库的创建者的这个想法。


Prism 7 引入了DialogService,一种全新的打开方式window。

  1. 创建新的 UserControl.xaml,它将代表 window 的内容。
    最简单的空内容可能是
<UserControl x:Class="YourUserControlName"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
    </Grid>
</UserControl>
  1. 为此视图创建相应的视图模型。
    此视图模型 必须 实现 IDialogAware 接口。
    这里有一个例子
public class BaseDialogViewModel : IDialogAware
{
    public string Title { get; }

    public event Action<IDialogResult> RequestClose;

    public virtual void RaiseRequestClose(IDialogResult dialogResult)
    {
        RequestClose?.Invoke(dialogResult);
    }

    public virtual bool CanCloseDialog()
    {
        return true;
    }

    public virtual void OnDialogClosed()
    {

    }

    public virtual void OnDialogOpened(IDialogParameters parameters)
    {

    }
}
  1. 你必须像这样注册对话框
public void RegisterTypes(IContainerRegistry containerRegistry)
{
    // replace 'YourUserControlName' with the class of the view which you created in setp 1
    containerRegistry.RegisterDialog<YourUserControlName>();
}
  1. 最后一步是随时显示对话框
    通常,您希望在用户单击按钮或执行操作时显示对话框,
    因此通常会在执行某些命令时执行以下代码,
    但同样取决于您.
_dialogService.ShowDialog(nameof(YourUserControlName), new DialogParameters(), action);
  • _dialogServiceIDialogService 类型并被注入到视图模型中,您将在其中使用它,示例
public MainViewModel(IDialogService dialogService) 
{
   this._dialogService = dialogService;
}

所有需要前面的步骤才能显示 window


还有一些其他可选步骤如果您需要(不需要)

  1. 您可以通过添加以下内容来指定 Window 的属性 prism:Dialog.WindowStyle xaml 元素
<UserControl x:Class="YourUserControlName"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True">

    <prism:Dialog.WindowStyle>
        <Style TargetType="Window">
            <Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterScreen" />
            <Setter Property="ResizeMode" Value="NoResize"/>
            <Setter Property="ShowInTaskbar" Value="False"/>
            <Setter Property="WindowState" Value="Maximized"/>
        </Style>
    </prism:Dialog.WindowStyle>

    <Grid>
    </Grid>
</UserControl>
  1. 您可以为显示 window
  2. 的功能创建一个扩展方法
public static class DialogServiceExtensions
{
    public static void ShowWindowTest(this IDialogService dialogService, Action<IDialogResult> action)
    {
        dialogService.ShowDialog(nameof(WindowTestView), new DialogParameters(), action);
    }
}

Prism 文档建议不需要它。


如果您想要使用 .NET Core 3.1 为新的 Prism 7 WPF 应用程序设置样板,那么您可以查看此 Github repository
它包含上述设置和许多其他用于启动 WPF Prism 应用程序的有用功能。

免责声明:我是存储库的作者