开发者

Firing PropertyChanged event in a complex, nested type in WPF

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.dep开发者_C百科arments)
      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?


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜