且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ViewModel 每个视图还是每个模型?

更新时间:2023-02-10 18:49:21

理论上,关系是

视图 n - 1 视图模型 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...

ViewModels 和 Views(在实践中)通常有 1 对 1 的关系.类似于 - 每个屏幕(或屏幕的一部分)实际上是一个配对的 View 和 ViewModel.我认为通常就像 - View 是 UI 层,ViewModel 是代码隐藏层.视图只是 XAML 文件 - 表示层.并且(***实践)其他所有内容都应该在 ViewModel 中——所有数据接收过程、所有命令、所有可变字段等.通过这种方式,您通常可以测试 ViewModel(通过单元测试).通常只有当您为桌面应用程序 (WPF)、Web 应用程序 (Silverlight) 和 Windows Phone 共享视图模型时,一个 ViewModel 才能拥有多个视图(实际上).像这样的东西.但通常 - 一个 ViewModel - 一个视图.如果一个 ViewModel 有多个 Views - 通常你会有很多维护问题...

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...