MVVMLight - ViewModel 引用其他 ViewModel

发布于 2024-11-07 20:24:30 字数 222 浏览 0 评论 0原文

您好,

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

許願樹丅啲祈禱 2024-11-14 20:24:30

在这种情况下,我首先将控制反转容器添加到应用程序中(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.

任谁 2024-11-14 20:24:30

有时我会构建一棵虚拟机树。例如:我通过将 Person 和 Hobbies VM 添加到 PersonH​​obbies VM 来创建 PersonH​​obbies 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文