MVVM-重用具有多个ViewModel的视图 [英] MVVM - Reuse Views with multiple ViewModels

查看:743
本文介绍了MVVM-重用具有多个ViewModel的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信MVVM的主要优点之一就是去耦,绑定和缺少引用使事情变得更加可重用.

我发现的所有MVVM示例都具有某种ViewModel,其ViewModel具有相同的命名,例如ExampleView具有ExampleViewModel.而且总是一对一的关系,一个视图,一个视图模型.

但是在我当前的项目中,我有一个要填写的表格,因此可以将数据添加到数据库中,而且用户可以选择在数据库上编辑数据,因此该表格视图可以透明地与两个人一起使用不同的ViewModel,一种用于添加数据,另一种用于编辑数据.我发现复制和粘贴整个View只是为了将其命名为ViewModel有点愚蠢,不仅如此,如果我需要更改某些内容,它总是必须是工作的两倍,并且可能会遗忘一些东西.

某些框架具有ViewModel定位器,该定位器将使用相同的命名约定将View与ViewModel自动绑定,这使我对具有许多不同ViewModel的View的可重用性表示怀疑.

我的问题基本上是:将一个View与不同的ViewModels一起使用是否存在问题?这是不好的做法吗?是否有针对此特定情况的命名约定?

由于缺乏可重用性的示例,这使我质疑这种做法的有效性.

解决方案

没有问题-视图是视图模型的已知知识,反之亦然.这对您所做的一切都很好.

但是,我会在两个视图模型中创建一个公共绑定属性的接口,然后在一个视图模型定位器中将实例公开为一个属性.这意味着您绑定到实现,但不在乎哪个.

如何切换实现取决于实例化视图的方式.

I believe one of the main benefits of MVVM is decoupling, the binding and lack of references makes things a lot more reusable.

All MVVM examples I find have some kind of View with a ViewModel with the same naming like ExampleView has a ExampleViewModel. And always a one to one relationship, one View, one ViewModel.

But in my current project I have a form to be filled so data can be added to the data base, also the user has the option to edit the data on the data base, so this form View can be used transparently with two different ViewModels, one for adding data and one for editing data. I find it a little stupid to copy and paste and entire View just to have it named after its ViewModel, and not only that, if I need to change something, it will always have to be twice the work and stuff might be forgotten.

Some frameworks have a ViewModel locator that will use this same naming convention to bind the View with the ViewModel automatically, and this makes me question the reusability of Views with many different ViewModels.

My question basically is: Is it there a problem in using one View with different ViewModels? Is it bad practice? Are there any naming conventions to this particular situation?

The lack of examples on reusability makes me question the validity of this practice.

解决方案

There is no problem - the view is knowledgable of the view model but not vice versa. This is fine with what you're doing.

I would however create an interface of the common binding properties in both view models then a view model locator to expose the instance as a property. That means your binding to the implementation but don't care which one.

How you toggle that implementation depends on how you instantiate your view.

这篇关于MVVM-重用具有多个ViewModel的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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