如何拥有多对"视图查看模型"? [英] How to have multiple pairs "View-ViewModel"?

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

问题描述

我建立是基于MVVM光强的应用程序。我在需要创建相同的视图的多个实例,每个人应该结合自己的视图模型。

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 实现的ViewModels为单身,同样的看法,因此不同的实例将绑定到同一个视图模型。

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

我可以创建在VMLocator视图模型作为非静态对象(如简单返回新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?

在此先感谢您的precious帮助。

Thanks in advance for your precious help.

干杯,

赞布罗塔。

Cheers,
Gianluca.

推荐答案

有没有存储的ViewModels作为ViewModelLocator单身义务,但它肯定使他们更容易找到如果认为是单过。显然,如果你有同样的观点类的多个实例,你就会有相同的视图模型类的多个实例,它不能是单身了。

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.

要跟踪视图模型的多个实例,可以实现在查找一个视图模型根据密钥ViewModelLocator的字典。键可以为视图的唯一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.

更新:通常你甚至不需要跟踪多个的ViewModels。例如,你可以有信使类,发送消息到使用发送过载一个给定的视图模型类的所有实例。所以,实施一个字典来跟踪虚拟机之前,问问自己,如果你真的需要它! ;)

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! ;)

希望帮助,
洛朗

Hope that helps, Laurent

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

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