簡體   English   中英

Prism ICommand從區域到外殼

[英]Prism ICommand from region to shell

我試圖創建一些區域,在其中一個區域中,我具有按鈕“ login”和綁定到的ICommand Login屬性。 因此,我想從shell訂閱此Login

我嘗試了PubSubEvent ,但我還需要CanExecute方法。

我發現的另一種解決方案是將靜態類與靜態命令一起使用。 我認為這不是一個好的模式。

從模式角度來看如何正確執行此操作?

編輯1

要分配區域,我在shell的視圖模型的承包商中調用此方法:

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

在視圖中,我使用此ViewModelLocator.AutoWireViewModel="True" ,因此無法注入外殼程序的視圖模型來為其訂閱事件。

您可以使用事件聚合器以分離的方式在不同模塊之間進行通信。 GitHub上有一個示例,位於此處: https : //github.com/PrismLibrary/Prism-Samples-Wpf/blob/master/EventAggregation/Desktop/ModuleA/AddFundPresenter.cs 如果您想了解事件聚合器模式及其在Prism中的應用方式的基礎知識,可以參考以下博客文章: https : //blog.magnusmontin.net/2014/02/28/using-the-event-aggregator視圖模型之間的通信模式

另一個選擇是使用共享服務: https : //social.msdn.microsoft.com/Forums/en-US/22907a0f-d805-4195-8272-7c284b72d2ee/example-of-using-shared-services-prism? forum = wpf 共享服務只是一個類,它以解耦的方式為多個模塊提供功能。 它應該實現一個接口,然后將其注冊到引導程序中的容器中,通常是單例。

在視圖中,我使用此ViewModelLocator.AutoWireViewModel =“ True”,因此無法注入外殼程序的視圖模型來為其訂閱事件。

好吧,如果您根本不希望在外殼程序的視圖模型中注入任何依賴項,則必須使用某種靜態類來獲取對EventAggregator或共享服務的引用。 有一個示例示例,說明如何從此處的靜態類公開EventAggregator: https ://rachel53461.wordpress.com/2011/10/09/simplifying-prisms-eventaggregator/

但是您可以通過覆蓋Bootstrapper的InitializeShell()方法輕松地將shell窗口注入所需的任何依賴關系,例如:

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-MainWindow沒有DataContext

但是,談到模式,您可能應該考慮將您的shell視圖模型類移動到模塊上,並將shell窗口保持為由子視圖組成的真正的shell。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM