views:

155

answers:

1

I have a class called DataStore and a list of Departments (an ObservableCollection), and each department again has a list of Products. Properties in the Product class that are changed also affect properties in the Department and DataStore class. How does each Product notify the Department it belongs to, and the DataStore (which is the mother class of all) that one or more of its properties have changed their values? Example: a product has a property NumberSoldToday and is bound. The Department has a property called TotalNumberOfProductsSold:

public int TotalNumberOfProductsSold
{
  get
  {
    int result = 0;
    foreach(Product p in this.products)
      result += p.NumberSoldToday;
    return result;
  }
}

And the data store has a property TotalProductsSold (for all departments):

public int TotalProductsSold
{
  get
  {
    int result = 0;
    foreach(Product p in this.deparments)
      result += p.TotalNumberOfProductsSold;
    return result;
  }
}

If all these properties are bound, and the innermost property changes, it must somehow notify that the value of the other 2 changed as well. How?

The only way I can see this happening is to hook up the PropertyChanged event in each class. Th event must also fire when deleting, adding to the collection of products and deparments, respectively.

Is there a better, more clever way to do this?

+1  A: 

Rather than calculating the value whenever it's asked for, you could set the value whenever something that should affect it changes. In this case you'd want to handle the this.deparments.CollectionChanged event, and do your calculation there. The TotalProductsSold property would just look like any other property, with a FireNotifyPropertyChanged("TotalProductsSold") call in its setter...

Rob Fonseca-Ensor
I see. Going back to my example above, lets say I subscribe to the CollectionChanged event in the Department. Does that event get fired when a property in one of the collection items (=Product) changes? Is that event not just for add/delete/move?
John