MVVM:薄的ViewModels和丰富的机型 [英] MVVM: Thin ViewModels and Rich Models

查看:135
本文介绍了MVVM:薄的ViewModels和丰富的机型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继续与MVVM模式,奋斗,在试图创建一个小型/中型项目的实际设计中,遇到了一些挑战。这些挑战之一是搞清楚如何让这个模式去耦带来的好处,而无需创建大量的重复性,难以维护的代码。

I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code.

我目前的策略一直以打造'富'模型类。他们充分认识到,他们将通过MVVM模式消耗和实现INotifyPropertyChanged,允许观察和继续认识他们可能总是在观察自己的藏品。我的视图模型类往往是薄的时候,居然需要进行改造,其中大部分他们的代码是RelayCommand处理的数据暴露唯一性。次愉快地结合任一的ViewModels或模型直接,这取决于是否需要任何数据转换。我使用AOP(通过Postsharp),以缓解INotifyPropertyChanged的痛苦,因此很容易使所有的这种方式我的模型类的富二代。

My current strategy has been to create 'rich' Model classes. They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation. My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers. Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required. I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way.

是否有显著的缺点使用该方法?我可以假设视​​图模型和视图是如此紧密耦合,如果我需要新的数据转换为View,我可以简单地把它根据需要添加到视图模型?

Are there significant disadvantages to using this approach? Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

推荐答案

我觉得INotifyPropertyChanged的上,当你期待它在你的VM和外部的势力同时操作您的手机型号是唯一有用的。

I think INotifyPropertyChanged on your model is only useful when you're expecting it to be operated on by your VM and external "forces" simultaneously.

我个人POCO模型的支持者。把任何特定的框架,脚手架进入我的模型会令我担心。当你把一个事件到模型类,你有你的模型的生命周期,系列化,存储等。例如,如果你从数据源老INotifyPropertyChanged的订阅重新创建你的对象是现在是无效的会发生什么情况仔细考虑可能出现的问题?

I'm personally a supporter of POCO models. Putting any framework-specific scaffolding into my model would make me worry. When you put an event into your model class you have to consider carefully possible issues with your model's life-cycle, serialization, storage etc. For example what happens if you recreate your object from data source and old INotifyPropertyChanged subscriptions are now invalid?

相若更好的地方的ObservableCollection是在VM,它可能消耗一个IEnumerable数据源,而目前只选择或特设筛选项目的看法。

Similarily better place for ObservableCollection is in the VM, which can consume an IEnumerable datasource, and present to the view only selected or ad hoc filtered items.

这篇关于MVVM:薄的ViewModels和丰富的机型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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