最好的解释方式是举例:
这是模型
public class Person
{
public int age;
public string name;
}
这是 View 模型
public class PersonVM
{
}
我的问题是:
vm 应该将人暴露给数据模板还是用他自己的属性封装模型属性?
最佳答案
关于这个问题还没有达成共识。例如,这是 Ward Bell 提出的关于 MVVM 的开放性问题之一 here :
Is the VM allowed to offer the V an unwrapped M-object (e.g., the raw Employee) ? Or must the M-object’s properties (if it is even permitted to have properties!) be exposed exclusively through the surface of a VM wrapper?
不直接在 VM 中公开模型的主要优点是:
您可以将它用作“类固醇转换器”,以一种方便的方式为 View 格式化模型值
您可以注入(inject)与用户界面相关的其他功能,例如 data validation messages , undo redo ,..
缺点是:
您将不得不复制大量代码以在 View 模型中公开所有模型属性。
如果您将 View 控件绑定(bind)到 viewmodels 属性,您将从 viewmodel 发送 propertyChanged 事件。但是,如果模型属性从不同于 viewmodel setter 的其他来源更改,会发生什么情况?然后它必须通知 View 模型,所以你以 2 个 OnPropertyChanged 结束,一个在模型中,一个在 View 模型中......非常复杂!
所以对我来说正确的答案是:这取决于您的要求。
关于c# - MVVM:VM 对象应该直接公开 M 对象,还是仅通过委托(delegate)给 M 的 getter 的 getter 公开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114555/