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

喜你入骨 提交于 2019-12-12 03:44:39

问题


Is there a way whereby I can identify a ChildViewModel instance, which was created by prism's ViewModelLocator, upon opening it's corresponding window?

I would like to trigger that the ChildViewModel should load it's data, based on parameters originating from the MasterViewModel.

In code, in MasterViewModel has an ICommand in a which is responsible for requesting opening a new child window by publishing an event, and there is a corresponding subscriber.

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

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

Notice that the MasterViewModel knows nothing about the UI implementation.

The the subscriber calls ShowWindow method on a custom WindowManager which basically resolves the View (Window in this instance) which corresponds to the ViewModel which was passed in.

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

The xaml for the window the appropiate

ViewModelLocator.AutoWireViewModel="True"

回答1:


Go for a view model-first style of navigation. If you pass a (child-)view model instance (instead of a type) to ShowWindow, you can create that with whatever data you need.

Probably, you pass the data around as payload of the OpenNewChildWindowPubSubEvent, and the subscriber then creates the view model. Or you create the view model immediately in the command and pass that on as payload of the event.

Anyway, don't resolve the view type from the view model type just to resolve the view model type from the view :-)

BTW, the ViewModelLocator is great and really simplifies things, but you don't want to use it here, because you're not navigating within one shell, but creating new windows. If you would, your view model would implement INavigationAware and you'd pass the data to the child view model as parameter to RequestNavigate...



来源:https://stackoverflow.com/questions/44420238/prism-viewmodellocator-creates-the-view-model-instances-but-how-can-i-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!