INotifyPropertyChanged and calculated property

Another solution is the one Robert Rossney proposed in this question:

WPF INotifyPropertyChanged for linked read-only properties

You can create a property dependency map (using his code samples):

private static Dictionary<string, string[]> _DependencyMap = 
new Dictionary<string, string[]>
{
   {"Foo", new[] { "Bar", "Baz" } },
};

and then do this in your OnPropertyChanged:

PropertyChanged(this, new PropertyChangedEventArgs(propertyName))
if (_DependencyMap.ContainsKey(propertyName))
{
   foreach (string p in _DependencyMap[propertyName])
   {
      PropertyChanged(this, new PropertyChangedEventArgs(p))
   }
}

You can even attach an attribute to tie the dependent property to the one it depends on. Something like:

[PropertyChangeDependsOn("Foo")]
public int Bar { get { return Foo * Foo; } }
[PropertyChangeDependsOn("Foo")]
public int Baz { get { return Foo * 2; } }

I haven't implemented the details of the attribute yet. I'd better get to working on that now.


It's fine to check to see if you should raise this event as well from any other member that may change the value, but only do so if you actually change the value.

You could encapsulate this in a method:

private void CheckTotalPrice(decimal oldPrice)
{
    if(this.TotalPrice != oldPrice)
    {
         this.RaisePropertyChanged("TotalPrice");
    }
}

Then you need to call that from your other mutating members:

var oldPrice = this.TotalPrice;
// mutate object here...
this.CheckTotalPrice(oldPrice);

Is it a good practice to call RaisePropertyChanged("TotalPrice") in the properties that affect to TotalPrice calculation?

No, it's not, it doesn't scale and (the fact that property should know everything that depends on it) is a maintenance nightmare

https://github.com/StephenCleary/CalculatedProperties is best formula engine as of now for MVVM (in my opinion) that notifies about changes of derived/calculated properties and supports any level of nesting, most importantly tree of dependencies can span across multiple objects and can dynamically change at runtime.

  public decimal ItemPrice 
  { 
    get { return Property.Get(0m); }
    set { Property.Set(value); }
  }

  public int Quantity 
  { 
    get { return Property.Get(0); }
    set { Property.Set(value); }
  }

  public decimal TotalPrice
  {
    get { return Property.Calculated(() => ItemPrice * Quantity); }    
  }

This is very similar to Excel formulas but for MVVM. ItemPrice nor Quantity don't know what depends on them and don't care about raising PropertyChanged for dependant TotalPrice. Tree of dependencies can have as many levels as needed.