Piero Alberto
Piero Alberto

Reputation: 3943

ObservableCollection: raising event when updating values

"Occurs when an item is added, removed, changed, moved, or the entire list is refreshed." This is written in MSDN, talking about CollectionChanged event... but.. what does it mean with "changed"??

I have an observableCollection. It's populated from db and it is binded in my view (i'm working with mvvm pattern).

So, I think: "well, from my view I edit my fields, binded with the observableCollection". With the debug, I see the fields updated, but... the event is not fired... why?

What does the msdn mean with "changed"? and, if this way is wrong, how can I trigger my action when the value of the observablecollection are updated in the way I explained before?

Upvotes: 0

Views: 440

Answers (2)

Sheridan
Sheridan

Reputation: 69979

You're confusing the INotifyCollectionChanged interface with the INotifyPropertyChanged interface. It sounds like you want to know when any property of any item in the collection changes. In order to make that happen, you will need to implement the INotifyPropertyChanged interface in your data type class and attach a handler to the INotifyPropertyChanged.PropertyChanged event:

item.PropertyChanged += Item_PropertyChanged;

private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    // The 'e.PropertyName' property changed
}

You can improve this further by extending the ObservableCollection<YourDataType> class and adding this code into that class:

public new void Add(T item)
{
    item.PropertyChanged += Item_PropertyChanged;
    base.Add(item);
}

...

public new bool Remove(T item)
{
    if (item == null) return false;
    item.PropertyChanged -= Item_PropertyChanged;
    return base.Remove(item);
}

There are also other methods that you should override in this way, but once you have, you can just let this class do all of the work for you... even better if you put it into some kind of generic base class. If you make that class also implement the INotifyPropertyChanged interface, then you can also 'forward' all property changes for convenience:

private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    NotifyPropertyChanged(e.PropertyName);
}

Upvotes: 0

Servy
Servy

Reputation: 203842

In this context changed means replacing the item at a certain index with another item, not mutating an existing item. Mutating an item in the collection is not a change in the collection, nor does it have a way of observing such changes in the general case.

Upvotes: 1

Related Questions