MVVM field set vs referenced event on INotifyPropertyChanged implementing classes

Viewed 30

If we have property which depends on another property (change to the first fires update of the second) we have two ways of doing this. We can make Dependent get only and call RaiseOnPropertyChanged(nameof(Dependent)). Or we can make Dependent with backing field, and instead just assign this value to dependent property DependentProperty = newValue. Which is more MVVM way?

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() { ... } 
}

Second approach:

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() { ... } 
}
1 Answers

I think approach 2 is more reasonable, because it is eaiser to chain events. Especially if chain is more complex and there are lots of start nodes.

Approach 1 has disadvantage, where You cannot encapsulate property computation inside that property, but in all properties which assign to it - but I think it is minor disadvantage, as You can encapsulate it in a function and call that function.

Related