WPF Prism将相同的viewmodel实例注入两个视图 [英] WPF Prism Inject same viewmodel instance into two views

查看:559
本文介绍了WPF Prism将相同的viewmodel实例注入两个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在WPF Prism应用程序中有两个单独的视图。如何通过依赖注入将 ViewModel 的相同实例注入到两个视图中?

So I have two separate views in a WPF Prism app. How can I inject the same instance of a ViewModel into both the views via Dependency Injection?

推荐答案

(我假设您使用的是直接提到DI的Unity,而不是说导入或类似内容)

(I assume you are using Unity as you mentioned DI directly and are not saying "Import" or similar)

您将必须在容器中将ViewModel注册为单例(使用ContainerControlledLifetimeManager),并照常进行注入。这样可以确保您在每次请求时都将获得相同的实例。
在这种情况下,一种有效的方法可能是使用命名注册,以防您想在其他地方注入相同的VM,但又不需要相同的实例。

You will have to register the ViewModel as a singleton (using a ContainerControlledLifetimeManager) in the container and have it injected as usual. This ensures that you will get the same instance whenever you request for it. A valid approach in this scenario might be to use a named registration in case you want to get the same VM injected elsewhere, but you don't need the same instance.

本文解释该怎么做。

这篇关于WPF Prism将相同的viewmodel实例注入两个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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