MVVMLight - ViewModel 引用其他 ViewModel
您好,
我正在使用 MVVMLight,我希望特定的虚拟机引用另一个虚拟机的属性。目前,我使用 ViewModelLocator.SomeViewModelStatic 来执行此操作。有时,我也想使用另一个视图模型的方法。还可以使用 ViewModelLocator.SomeViewModelStatic 来使用其他 ViewModel 的方法。
这是 ViewModel 之间通信的正确方式吗?
HI,
I'm using MVVMLight and i would like a particular VM to reference to another VM's property. Currently, i using the ViewModelLocator.SomeViewModelStatic to do it. At times, i would also like to use the methods of another viewmodel. And also using the ViewModelLocator.SomeViewModelStatic to use other ViewModels' methods.
Is this the correct way of communicating between ViewModels?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我首先将控制反转容器添加到应用程序中(Autofac 、Ninject 甚至 MEF(如果您熟悉))并在所有 ViewModels 中注册(您可以手动执行此操作,或者相同的 IoC 容器可以在程序集中查找特定类)和服务。然后我将实现 ViewModelLocator 来与 IoC 一起使用,这样 ViewModel 将由它创建(然后每个依赖项都将通过依赖项注入来解决,您所需要担心的就是将所有内容注册到IoC)
通过使用 IoC,您还可以使用工厂方法,它可以在 ViewModel 中为您创建实例。
In such case I would start by adding Inversion of Control container to the application (Autofac, Ninject or even MEF (if you're familiar with it)) and registering within all ViewModels (you can do it manually or same IoC containers can look for specific classes in the assemblies) and Services. Then I would implement
ViewModelLocator
to work with the IoC in such a way that ViewModels would be created by it (then every dependency would be resolved by Dependency Injection and all you have to worry about is to register everything in IoC)By using IoC you can also use factory methods, that can create instances for you in ViewModels.
有时我会构建一棵虚拟机树。例如:我通过将 Person 和 Hobbies VM 添加到 PersonHobbies VM 来创建 PersonHobbies VM。该类将包含跨越其他虚拟机的所有命令。
我犹豫是否将 Hobbies VM 链接到 Person VM(或反向),因为在没有 Person VM(或反向)的情况下使用 Hobbies VM 会变得更加困难。
同样,我创建视图:在本例中,我可以为人员和爱好创建视图,并在构造人员爱好视图时使用这些视图。
At times I build a tree of VM's. E.g.: I create a PersonHobbies VM by adding both a Person and a Hobbies VM to the PersonHobbies VM. This class will have all the commands that span both other VM's.
I hesitate to link the Hobbies VM to the Person VM (or reverse) because it will become harder to use the Hobbies VM without the Person VM (or reverse).
Similarly I create Views: In this example I could create Views for both Person and Hobbies and use these Views when constructing the PersonHobbies View.