让我思考 MEF:如何加载视图(模型)?
我正在学习 prism V4 使用 MEF 加载我的模块。加载模块确实有效,但在一个模块中我想加载一个 View/ViewModel (MVVM),并且真的不知道如何让 MEF 为我解决所有这些问题。
首先:我需要如何标记 ViewModel(我遵循 StockTraderRI 示例),以便它不会在启动时加载,而是可以在运行时加载到某个区域中?
第二:如何使用 MEF 加载 ViewModel 以便它连接到相应的接口?
MEF 对于启动时标记为 [Export] 的事情做得很好,但我不知道如何在运行时实现这一点。
I'm learning prism V4 using MEF to load my modules. Loading modules does work, but in one module I want to load a View/ViewModel (MVVM) and don't really know how I get MEF to resolve all this stuff for me.
First: how do I need to mark the ViewModel (I follow the StockTraderRI example) so it is not loaded on startup but instead can be loaded during runtime into a region?
Second: how do I load the ViewModel using MEF so it gets connected to the corresponding interfaces?
MEF does this very nicely for things on startup which are marked as [Export], but I got no idea how to achieve this during runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用所谓的Lazy Export,这样接口就不会被解析直到您明确使用它。
如果您需要创建多个实例,MEF 对此支持不是特别好。您可以自己进行发现和实例化,也可以像这样定义 Export:
缺点是现在无论您需要创建实例,都需要引用实际的 Container 实例。然后你可以这样做:
编辑:好的,我想我更好地理解你所追求的。以下是我通常解决此问题的方法:
我将 View 对象实现为 UserControl 实例,并且不在其代码或 XAML 中的任何位置设置 DataContext。
我创建一个从 ViewModel 的类型绑定到 UserControl 的 DataTemplate。
在我的 MainViewModel(或与托管区域的视图相对应的任何内容)上,我公开了一个通用 RegionX 对象(如果我的所有 ViewModel 将共享一些通用功能,则可能键入一个接口,但对象工作正常)。
我创建一个 ContentPresenter,其中内容绑定到 RegionX 属性。
现在,我的 MainViewModel 可以导入与 RegionX 可能托管的 ViewModel 类型相对应的不同 ViewModel 实例。当我想要切换区域中的“活动”视图时,我只需将 RegionX 设置为相应的 ViewModel。
You can use what is known as a Lazy Export so that the interface is not resolved until you explicitly use it.
If you need to create multiple instances, MEF doesn't support this particularly well. You can either do your own discovery and instantiation, or you can define the Export like this:
The downside is that now wherever you need to create the instance, you need to have a reference to the actual Container instance. Then you can do:
EDIT: Okay, I think I understand better what you're after. Here is how I've typically resolved this issue:
I implement my View objects as UserControl instances and don't set a DataContext anywhere in their code or XAML.
I create a DataTemplate that binds from the Type of the ViewModel to the UserControl.
On my MainViewModel (or whatever corresponds to the View hosting the regions), I expose a general RegionX Object (possibly typed to an interface if all of my ViewModels will share some common functionality, but Object works fine).
I create a ContentPresenter with Content bound to the RegionX property.
Now my MainViewModel can import different ViewModel instances corresponding to the types of ViewModels that might be hosted by the RegionX. When I want to switch the 'active' View in the region, I simply set RegionX to the corresponding ViewModel.