Prism ICommand 从区域到 shell

Prism ICommand from region to shell

我试图创建一些区域,在其中一个区域中,我绑定了按钮 "login" 和 ICommand Login 属性。所以我想从 shell.

订阅这个 Login

我尝试了PubSubEvent,但我还需要CanExecute方法。

我找到的另一个解决方案是将静态 class 与静态命令一起使用。我认为这不是一个好的模式。

如何从模式的角度做到这一点?

编辑 1

为了分配区域,我在 shell 的视图模型的构造函数中调用了它:

regionManager.RegisterViewWithRegion("MainContent", typeof(LoginArea));

鉴于我使用了这个 ViewModelLocator.AutoWireViewModel="True",所以我无法注入 shell 的视图模型来订阅它的事件。

您可以使用事件聚合器以解耦的方式在不同模块之间进行通信。 GitHub 上有一个示例:https://github.com/PrismLibrary/Prism-Samples-Wpf/blob/master/EventAggregation/Desktop/ModuleA/AddFundPresenter.cs. If you want the basics on the event aggregator pattern and how it is applied in Prism, you could refer to the following blog post: https://blog.magnusmontin.net/2014/02/28/using-the-event-aggregator-pattern-to-communicate-between-view-models/.

另一种选择是使用共享服务:https://social.msdn.microsoft.com/Forums/en-US/22907a0f-d805-4195-8272-7c284b72d2ee/example-of-using-shared-services-prism?forum=wpf。共享服务只是一个 class,它以解耦的方式为多个模块提供功能。它应该实现一个接口,然后在引导程序中将其注册到容器中,通常作为单例。

And in view I use this ViewModelLocator.AutoWireViewModel="True", so I could not inject my shell's view model to subscribe events to it.

好吧,如果你根本不希望 shell 的视图模型被注入任何依赖项,你将不得不使用某种静态 class 来获取对EventAggregator 或共享服务。这里有一个示例,说明如何从静态 class 公开 EventAggregator:https://rachel53461.wordpress.com/2011/10/09/simplifying-prisms-eventaggregator/

但是您可以通过覆盖引导程序的 InitializeShell() 方法,轻松地向 shell window 注入您需要的任何依赖项,例如:

class Bootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void InitializeShell()
    {
        RegisterTypeIfMissing(typeof(IEventAggregator), typeof(EventAggregator), true);
        Application.Current.MainWindow.DataContext = new MainWindowViewModel(Container.Resolve<IEventAggregator>());
        Application.Current.MainWindow.Show();
    }
}

ViewModelLocator.AutoWireViewModel 属性 无论如何都用于 UserControl 视图:

ViewModelLocator.AutoWireViewModel - No DataContext for MainWindow

但是,说到模式,您可能应该考虑将 shell 视图模型 class 移动到一个模块中,并将 shell window 保持为真实的 shell 由子视图组成。