我的代码看起来有点像下面这样:
public class MyModel {
public string MyProperty { get; set; }
}
public class MyViewModel: ObservableValidator {
private mModelInstance;
public MyViewModel(MyModel modelInstance){
this.mModelInstance = modelInstance;
}
[MinLength(20)]
public string MyProperty {
get => mModelInstance.MyProperty;
set => SetProperty(ref mModelInstance.MyProperty, value, validate = true); // This doesn't work because mModelInstance.MyProperty is a Property which cannot be passed as ref
}
}
现在我看到了几种可能的方法来做到这一点,但不确定哪种是最好的:
将 Validation 和 PropertyChanged 移至 Model,并为 MyModel 中的 MyProperty 引入私有支持字段。然后,我将 ModelInstance 公开为 ViewModel 中的属性。这允许我在 MyModel.MyProperty setter 中使用
SetProperty(ref mMyProperty, value, validate = true)
。
我可以将 MyModel.MyProperty 更改为公共字段而不是公共属性。然而,(据我所知)这是一个不好的做法。这在 POCO 中也很糟糕吗?
我可以在 MyViewModel.MyProperty setter 中执行以下操作,而不是一次调用
SetProperty
:
set {
mModelInstance.MyProperty = value;
OnPropertyChanged();
ValidateProperty(value);
}
这有效,我的模型没有改变(即仍然具有公共属性,而不是字段)。这是我会选择的方法,但事实上我有 3 个单独的语句而不是 MVVM-Toolkit 提供的语句,这让我有点犹豫。
根据我的经验,视图模型定义了自己的支持字段以及公共方法(例如 Save())来提交对模型的更改:
如果有多个属性,很容易创建无效的值组合,并且不知道模型可以如何处理它。
public class MyViewModel: ObservableValidator {
private mModelInstance;
public MyViewModel(MyModel modelInstance){
this.mModelInstance = modelInstance;
}
private string _myProperty;
[MinLength(20)]
public string MyProperty {
get => _myProperty;
set => SetProperty(ref _myProperty, value, validate = true);
}
public void Save() {
mModelInstance.MyProperty = _myProperty;
}
}