簡體   English   中英

棱鏡:ViewModelLocator創建視圖模型實例,但是我該如何定位呢?

[英]Prism: ViewModelLocator creates the view model instance(s) but how can I target it?

有沒有一種方法可以在打開對應的窗口時識別由棱鏡的ViewModelLocator創建的ChildViewModel實例?

我想根據源自MasterViewModel的參數觸發ChildViewModel應該加載其數據。

在代碼中, MasterViewModel有一個ICommand ,該ICommand負責通過發布事件來請求打開新的子窗口,並且有一個相應的訂戶。

public ICommand OpenNewChildWindow()
{
    Publish(new OpenNewChildWindowPubSubEvent());

    // Maybe I can publish a new PubSubEvent here
    // but how can I target just the recently created ChildViewModel?
}

請注意, MasterViewModel對UI實現一無所知。

訂閱者在自定義WindowManager上調用ShowWindow方法,該方法基本上解析與傳入的ViewModel對應的View(在此實例中為Window)。

public void ShowWindow(Type viewModelType)
{
   Type view = ResolveView(viewModelType);
   Window w = (Window)Activator.CreateInstance(view);
   w.Show();
}

適用於窗口的xaml

ViewModelLocator.AutoWireViewModel="True"

選擇視圖模型優先的導航樣式。 如果將(子視圖)視圖模型實例(而不是類型)傳遞給ShowWindow ,則可以使用所需的任何數據來創建它。

可能您將數據作為OpenNewChildWindowPubSubEvent有效負載OpenNewChildWindowPubSubEvent ,然后訂閱者將創建視圖模型。 或者,您可以在命令中立即創建視圖模型,並將其作為事件的有效負載傳遞。

無論如何,不​​要僅僅從視圖模型類型中解析視圖類型,就從視圖中解析視圖模型類型:-)

順便說一句, ViewModelLocator很棒,確實可以簡化事情,但是您不想在這里使用它,因為您不是一個shell中導航,而是創建新窗口。 如果願意,您的視圖模型將實現INavigationAware ,並將數據作為RequestNavigate參數傳遞給子視圖模型...

暫無
暫無

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

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