This assumes that the invoice and the client implement IPropertyChanged. Just change your collection to ObservableCollection and view the CollectionChanged property.
When adding new invoices, attach an event handler to the PropertyChanged event of this invoice. When an item is removed from the collection, delete this event handler.
Then just call the NotifyPropertyChanged function in the TotalOpenInvoices property.
For example (not fully tested, but should be close):
Invoice
public class Invoice : INotifyPropertyChanged { private bool payedInFull = false; public bool PayedInFull { get { return payedInFull; } set { payedInFull = value; NotifyPropertyChanged("PayedInFull"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion }
Customer
public class Customer : INotifyPropertyChanged { public Customer() { this.Invoices.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Invoices_CollectionChanged); } ObservableCollection<Invoice> Invoices { get; set; } public int TotalOpenInvoices { get { if (Invoices != null) return (from i in Invoices where i.PayedInFull == false select i).Count(); else return 0; } } void Invoices_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { foreach (Invoice invoice in e.NewItems) { invoice.PropertyChanged += new PropertyChangedEventHandler(invoice_PropertyChanged); NotifyPropertyChanged("TotalOpenInvoices"); } foreach (Invoice invoice in e.OldItems) { invoice.PropertyChanged -= new PropertyChangedEventHandler(invoice_PropertyChanged); NotifyPropertyChanged("TotalOpenInvoices"); } } void invoice_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "PayedInFull") NotifyPropertyChanged("TotalOpenInvoices"); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion }
Please note that each class can be assigned to one class that implements INotifyPropertyChanged, for example, the ViewModelBase class, but this is not necessary for this example.
source share