如何使用 MEF 在 MVVM 中切换视图
我有一个单例 Model 和 ViewModel 对象,并且希望以编程方式创建 WPF 视图并将其附加到它们,一次一个。可以动态创建视图,例如通过选择菜单项(某处)。新创建的视图将处理查看 ViewModel 的任何旧视图。然后它将使自己成为该 ViewModel 的当前视图,并将其显示在某个 WPF 窗口中,作为视图 UserControl 的容器。我正在使用 MEF 进行 IoC。重要的是 Model 和 ViewModel 对象仅创建一次。使用 MEF 实现此目的的方法是什么?
I have a singleton Model and ViewModel objects and would like to programmatically create and attach WPF views to them, one at a time. Views can be created dynamically, say by selecting a menu item (somewhere). Newly created view would dispose of any old view looking at a ViewModel. Then it would make itself a current view of that ViewModel, displaying it in some WPF window serving as a container for view UserControl. I am using MEF for IoC. It is important that Model and ViewModel objects are created only once. What would be the way to accomplish this using MEF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以查看 WPF 应用程序框架 (WAF)。他们展示了如何使用 MVVM 和 MEF 切换视图。
You might have a look at the ViewModel and Writer sample applications of the WPF Application Framework (WAF). They show how to switch a view using MVVM and MEF.
我在我的测试应用程序中使用视图模型优先方法。所以我通过 mef 实例化 viewmodel,然后 wpf + datatemplates 完成剩下的工作。我所要做的就是将我的实际视图模型绑定到 contentcontrol.content。
你说 ViewModel 对象只创建一次很重要。您可以使用 mef 和 CreationPolicy.Shared 或 Lazy<> 来实现此目的进口。考虑到这一点,我认为 ViewModel-First 是你应该走的路。它很简单,您不需要额外的定位器或其他任何东西:)
I use viewmodel first approach in my testapps. so i instantiate viewmodel via mef and then wpf + datatemplates do the rest. all i have to do is binding my actual viewmodel to the contentcontrol.content.
you say that its important that ViewModel objects just created once. you achieve this with mef and creationPolicy.Shared or Lazy<> import. with this in mind i think ViewModel-First is the way you should go. its straightforward and you need no extra locator or wathever :)