Question

I am having trouble with getting a total count calculation to run when the value of one of the items in a collection is changed. I do have the INotifyPropertChanged event on the class and the collection is an ObservableCollection<T>. I have also tried a BindingList<T> without luck.

public class Inventory
{
    public ObservableCollection<Item> Items { get; set; }
    public int TotalCount {
        get { return Items.Select(i => i.Count).Sum(); }
    }

}

public class Item : INotifyPropertyChanged {

    private int count;
    public int Count {
        get { return count; }
        set {
            count = value;
            NotifyPropertyChanged("Count");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName) {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

My next though was to register an event handler for each item that is added to the collection, but I am not quite sure how to manage the events that may have already been registered. It seems I am missing something simple here, can anyone point it out?

BTW, I am data binding in WPF to this class.

Was it helpful?

Solution 2

Here is the code for that "tedious task" ... first in the Inventory constructor:

Items.CollectionChanged += Items_CollectionChanged;

Then in the body of the Inventory class:

void Items_CollectionChanged(object s, NotifyCollectionChangedEventArgs e) {
    if (e.OldItems != null)
        foreach (INotifyPropertyChanged item in e.OldItems)
            item.PropertyChanged -= ItemPropertyChanged;
    if (e.NewItems != null)
        foreach (INotifyPropertyChanged item in e.NewItems)
            item.PropertyChanged += ItemPropertyChanged;
}

void ItemPropertyChanged(object s, PropertyChangedEventArgs e) {
    if (e.PropertyName == "Count")
        NotifyPropertyChanged("TotalCount");
}

OTHER TIPS

You need to handle CollectionChanged event, subscribe to newly added items and unsubscribe from deleted items. This is a tedious task to do it every time, so you can subclass ObservableCollection and override OnCollectionChanged.

For an example implementation, see GitHub/Alba.Framework/NotifyingCollection(T).cs (it has some dependencies within the project, so you won't be able to copy-paste it though). There's a simpler implementation on StackOverflow somewhere, but I can't find it at the moment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top