C# INotifyPropertyChanged实现类上的MVVM字段集vs引用事件
如果我们有依赖于另一个属性的属性(第一个属性的更改是第二个属性的更新),我们有两种方法。我们可以使C# INotifyPropertyChanged实现类上的MVVM字段集vs引用事件,c#,mvvm,inotifypropertychanged,C#,Mvvm,Inotifypropertychanged,如果我们有依赖于另一个属性的属性(第一个属性的更改是第二个属性的更新),我们有两种方法。我们可以使Dependentget only并调用RaiseOnPropertyChanged(nameof(Dependent))。或者我们可以使用backing字段设置Dependent,只需将此值分配给Dependent属性DependentProperty=newValue。哪种方式更适合MVVM class Approach1 : INotifyPropertyChanged { priva
Dependent
get only并调用RaiseOnPropertyChanged(nameof(Dependent))
。或者我们可以使用backing字段设置Dependent
,只需将此值分配给Dependent属性DependentProperty=newValue
。哪种方式更适合MVVM
class Approach1 : INotifyPropertyChanged {
private object _primary;
public object Primary {
get { return _primary; }
set {
if(_primary != value) {
_primary = value;
RaiseOnPropertyChanged(nameof(Dependent));
}
}
public object Dependent {
get { return computeValue(); }
}
private object computeValue() { ... }
}
第二种方法:
class Approach2 : INotifyPropertyChanged {
private object _primary;
public object Primary {
get { return _primary; }
set {
if(_primary != value) {
_primary = value;
RaiseOnPropertyChanged();
Dependent = computeValue();
}
}
private object _dependent;
public object Dependent {
get { return _dependent; }
private set { if(_dependent != value) {
Dependent = value;
RaiseOnPropertyChanged();
}
}
private object computeValue() { ... }
}
我认为方法2更合理,因为它是连锁事件的始作俑者。特别是当链更复杂,并且有很多起始节点时 方法1有一个缺点,即不能将属性计算封装在该属性中,而是封装在分配给它的所有属性中——但我认为这是一个小缺点,因为可以将其封装在函数中并调用该函数