棱镜:ViewModelLocator创建视图模型实例,但是我该如何定位呢? [英] Prism: ViewModelLocator creates the view model instance(s) but how can I target it?

查看:130
本文介绍了棱镜:ViewModelLocator创建视图模型实例,但是我该如何定位呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在打开对应的窗口时识别由棱镜的ViewModelLocator创建的ChildViewModel实例?

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

我希望基于MasterViewModel的参数来触发ChildViewModel加载其数据.

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

在代码中,MasterViewModel中的ICommand中有一个ICommand,它负责通过发布事件来请求打开新的子窗口,并且有一个相应的订户.

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?
}

请注意,MasterViewModel对UI实现一无所知.

Notice that the MasterViewModel knows nothing about the UI implementation.

订阅者在自定义WindowManager上调用ShowWindow方法,该方法基本上解析了与传入的ViewModel相对应的View(在这种情况下为Window).

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();
}

适当的窗口xaml

ViewModelLocator.AutoWireViewModel="True"

推荐答案

转到视图模型优先的导航样式.如果将(子视图)视图模型实例(而不是类型)传递给ShowWindow,则可以使用所需的任何数据来创建它.

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.

可能您将数据作为OpenNewChildWindowPubSubEvent的有效负载传递,然后订阅者创建了视图模型.或者,您可以在命令中立即创建视图模型,并将其作为事件的有效负载传递.

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 :-)

顺便说一句,ViewModelLocator非常棒,确实可以简化事情,但是您不想在这里使用它,因为您不是在 内导航,而是创建了新窗口.如果愿意,您的视图模型将实现INavigationAware,并将数据作为RequestNavigate ...

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...

这篇关于棱镜:ViewModelLocator创建视图模型实例,但是我该如何定位呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆