每个视图或每个模型的ViewModel? [英] ViewModel per View or per Model?

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

问题描述

在MVVM模式中,每个视图仅存在一个ViewModel,还是每个模型仅存在一个ViewModel?

In the MVVM Pattern, is there exactly one ViewModel per View or is there exactly one ViewModel per Model?

推荐答案

从理论上讲,关系是

视图n-1个ViewModel n-1个模型

View n - 1 ViewModel n - 1 Model

我知道,很多人会咬我并殴打我,但是...在实践中...

I know, a lot of people will bite and beat me, but... In practice...

通常,在业务应用程序中,存在数据访问层(DAL). DAL实体经常是您的模型.有时,您应该使用其他类包装这些实体,以提供扩展功能或某些其他属性.也许您有自己的模型...

Very often, in business applications, there is data access layer (DAL). And very often entities from DAL are your Models. Sometimes you should wrap those entities with additional classes to provide extended functionality or maybe some additional properties. Maybe you have your own Models...

ViewModel和View(实际上)通常具有1到1的关系.有点像-每个屏幕(或屏幕的一部分)实际上都是成对的View和ViewModel.我认为通常只是-View是UI层,而ViewModel是代码隐藏层.视图只是XAML文件-表示层.并且(最佳实践)其他所有内容都应包含在ViewModel中-所有数据接收进程,所有命令,所有可更改的字段等.通过这种方式,您通常可以测试ViewModel(使用单元测试).一个ViewModel(实际上)通常只能在共享了ViewModel的情况下拥有多个View,例如,DesktopApplication(WPF),Web Application(Silverlight)和Windows Phone.这样的事情.但通常-一个ViewModel-一个视图.如果一个ViewModel有多个View,通常会遇到很多维护问题...

ViewModels and Views (in practice) usually have 1 to 1 relationship. Something like - every screen (or part of screen) is actually a paired View and ViewModel. I think usually just something like - View is UI layer and ViewModel is code-behind level. View is just XAML file - presentation layer. And (the best practice) everything else should be in ViewModel - all data receiving processes, all commands, all changable fields etc. This way you can usually test ViewModel (with unit testing). One ViewModel can have several Views (in practice) usually only when you have shared ViewModels for, for example, DesktopApplication (WPF), Web Application (Silverlight) and Windows Phone. Something like this. But usually - one ViewModel - one View. If you have several Views for one ViewModel - usually you will have a lot of maintaince problems...

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

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