为什么在 Silverlight MVVM 中通过 ViewModel 公开 Model 不好? [英] Why it's not good to expose Model through ViewModel in Silverlight MVVM?

查看:35
本文介绍了为什么在 Silverlight MVVM 中通过 ViewModel 公开 Model 不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我使用 MVVM 开发 WPF 应用程序而言,我从不通过 viewmodel 的公共属性公开模型.无论如何,在我刚刚来到 Silverlight 和 WCF RIA 的世界之后,我发现了实现数据验证的新方法,这是必需属性所说的.(还有其他属性)

As far as I develop WPF application with MVVM, I never expose model through viewmodel's public property. Anyway, after I just come to world of Silverlight and WCF RIA I found new method to achieve data validation, that's being said by Required attribute. (there are others attributes as well)

这次不用在 viewmodel 内部创建验证逻辑,我几乎可以在模型内部完成验证逻辑.

This time instead of create validation logic inside viewmodel, I can do almost of validation logic inside the model itself.

public class TestUserPM {
    [Key]
    public int ID { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string Email { get; set; }
}

之后,我需要在 ViewModel 中公开 TestUserPM 类型的公共属性,并让 View 直接绑定到模型.

After that, all I need in ViewModel is expose public property of TestUserPM's type and let View binding directly to the model.

我认为这不是优雅的解决方案,但它可以工作,并且不需要在 viewmodel 属性中创建繁琐的验证.

I think this is not elegant solution but it can work and it has no need to create tedious validation inside viewmodel property.

这种方法有什么缺点吗?

Are there any down-sides of this method?

更新 1

我刚刚发现了 1 个缺点,可能有解决方案.我想绑定按钮的命令,例如,按钮保存到 ViewModel 中的命令,但是当且仅当所有信息都有效时,该按钮才能执行.根据我对 WPF MVVM 的经验,我有帮助类,我将在 IDataErrorInfopublic string this[string columnName] 中调用 OnCanExecuteChanged().

I just found 1 down-side, may be it has solution out there. I want to binding Button's Command, for example, button save to Command in ViewModel but this button can execute if and only if all informations is valid. From my experience with WPF MVVM which I've helper class I'll call OnCanExecuteChanged() inside public string this[string columnName] of IDataErrorInfo.

我该如何处理这种需求?

How can I handle with this kind of requirement?

推荐答案

我一直通过 ViewModel 暴露 Model,只是为了让事情变得简单而不是重复自己 (DRY).

I expose Model through ViewModel all the time, just to keep things simple and to not repeat myself (DRY).

唯一避免需要在模型中添加属性以适应 UI(如 Benjamin 所述)的唯一方法是将模型保留为 viewModel 的属性,这样您就可以向 viewModel 添加属性,而不会弄乱模型.

The only thing to avoid the need to add properties in the model to adapt to the UI (as Benjamin notes), is to keep the model as a propery of the viewModel, so you can add properties to the viewModel, without messing the model.

即:ViewModel 是 DataContext,它有一个返回模型的 Model 属性

ie: The ViewModel is the DataContext and it has a Model property returning the model

<TextBlock Text={Binding Path=Model.Name} />
<TextBlock Text={Binding Path=Model.Address} />

这篇关于为什么在 Silverlight MVVM 中通过 ViewModel 公开 Model 不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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