如何拥有多对“View-ViewModel"? [英] How to have multiple pairs "View-ViewModel"?

查看:12
本文介绍了如何拥有多对“View-ViewModel"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个基于 MVVM-Light 的应用程序.我需要为同一个 View 创建多个实例,每个实例都应该绑定到自己的 ViewModel.

I am building an application that is based on MVVM-Light. I am in the need of creating multiple instances of the same View, and each one should bind to its own ViewModel.

默认的 ViewModelLocator 将 ViewModel 实现为单例,因此同一个 View 的不同实例将绑定到同一个 ViewModel.

The default ViewModelLocator implements ViewModels as singletons, therefore different instances of the same View will bind to the same ViewModel.

我可以在 VMLocator 中将 ViewModel 创建为非静态对象(就像返回 new VM()... 一样简单),但这只能部分帮助我.事实上,我仍然需要跟踪打开的窗口.然而,每个窗口可能会打开几个其他窗口(尽管是不同类型的).在这种情况下,我可能需要对父视图及其所有子视图执行一些操作.例如,在关闭视图 P 之前,我可能想关闭它的所有子项(视图 C1、视图 C2 等).

I could create the ViewModel in the VMLocator as a non-static object (as simple as returning new VM()...), but that would only partially help me. In fact, I still need to keep track of the opened windows. Nevertheless, each window might open several other windows (of a different kind, though). In this situation I might need to execute some operation on the parent View and all its children. For example before closing the View P, I might want to close all its children (view C1, view C2, etc.).

因此,有没有简单易行的方法来实现这一目标?或者您有什么最佳实践建议我遵循?

Hence, is there any simple and easy way to achieve this? Or is there any best practice you would advice me to follow?

预先感谢您的宝贵帮助.

Thanks in advance for your precious help.

干杯,
吉安卢卡.

Cheers,
Gianluca.

推荐答案

没有义务将 ViewModel 作为单例存储在 ViewModelLocator 中,但如果视图也是单例,这肯定会让它们更容易找到/强>.很明显,如果你有同一个View类的多个实例,你就会有同一个ViewModel类的多个实例,它就不能再是单例了.

There is no obligation to store the ViewModels as singletons in the ViewModelLocator, but it certainly makes them easier to find if the view is a singleton too. Obviously, if you have multiple instances of the same View class, you will have multiple instances of the same ViewModel class, and it cannot be a singleton anymore.

为了跟踪 ViewModel 的多个实例,您可以在 ViewModelLocator 中实现一个字典,根据键查找 ViewModel.例如,键可以是视图的唯一 ID.获取视图后,检索其键,然后从定位器中检索视图模型.

To keep track of the multiple instances of the ViewModel, you can implement a dictionary in the ViewModelLocator that looks up for a ViewModel according to a key. The key can be a unique ID for the view, for example. Once you get hold of the view, retrieve its key and then retrieve the viewmodel from the locator.

更新:通常您甚至不需要跟踪多个视图模型.例如,您可以让 Messenger 类使用 Send 重载向给定视图模型类的所有实例发送消息.因此,在使用字典来跟踪 VM 之前,先问问自己是否真的需要它!;)

Update: Often you don't even need to track multiple viewmodels. For instance, you can have the Messenger class send a message to all instances of a given viewmodel class using the Send overload. So before implementing a dictionary to keep track of the VMs, ask yourself if you really need it! ;)

希望有所帮助,洛朗

这篇关于如何拥有多对“View-ViewModel"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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