MVVM:VM对象应该直接公开M对象,还是仅通过委派给M的getter的getter公开? [英] MVVM: Should a VM object expose an M object directly, or only through getters delegating to M's getters?

查看:68
本文介绍了MVVM:VM对象应该直接公开M对象,还是仅通过委派给M的getter的getter公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的解释方法是举个例子:

the best way to explain is with example so:

这是模型

public class Person 
{
    public int age;
    public string name;
}

这是视图模型

public class PersonVM
{    
}

我的问题是:
虚拟机应该将人员暴露给数据模板还是用自己的属性封装模型属性?

my question is:
should the vm expose the person to the data template or encapsulate the model properties with his own properties?

推荐答案

视图模型应声明其自己的属性,并从视图中隐藏模型的详细信息.这为您提供了最大的灵活性,并有助于防止视图模型类型的问题泄漏到模型类中.通常,您的视图模型类通过委派来封装模型.例如,

The view model should declare its own properties and hide the specifics of the model from the view. This gives you the most flexibility, and helps keep view model-type issues from leaking into the model classes. Usually your view model classes encapsulate the model by delegation. For example,

class PersonModel {
    public string Name { get; set; }
}

class PersonViewModel {
    private PersonModel Person { get; set;}
    public string Name { get { return this.Person.Name; } }
    public bool IsSelected { get; set; } // example of state exposed by view model

    public PersonViewModel(PersonModel person) {
        this.Person = person;
    }
}

请记住:模型应该不了解使用它的视图模型,而视图模型也不应该了解使用它的视图.该视图对潜伏在后台的模型一无所知.因此,将模型封装在视图模型的属性后面.

Remember: the model shouldn't know anything about the view model that is consuming it, and the view model shouldn't know anything about the view that is consuming it. The view should know nothing about the models lurking in the background. Thus, encapsulate the model behind properties in the view model.

这篇关于MVVM:VM对象应该直接公开M对象,还是仅通过委派给M的getter的getter公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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