1

Possible Duplicate:
ObservableCollection that also monitors changes on the elements in collection

I have an application in WPF but I want to convert (all or some part) into MVVM.

I created a viewmodel which points to some ObservableCollections to be shown in the list view (one at a time, can be changed with radio buttons).

When the collections are changed I get a notification, however I don't get a notification when one of the items inside a collection is changed (i.e. IsSelected is changed from false/true or vice versa).

The only way I can see to make it work is to subscribe to the notifypropertychanged event handler for each of the items and when a new selection is made to remove the subscriptions and subscribe to the events of another collection, but this seems at least not the most ideal solution.

What solution is right for this problem? I checked some similar posts but they seem to be just a bit different.

Community
  • 1
  • 1
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
  • what do you want to achieve when `IsSelected` get changed? – Bolu Feb 03 '12 at 10:25
  • Take a look at this implementation of a [ObservableCollection that also monitors changes on the elements in collection](http://stackoverflow.com/a/269113/620360). – LPL Feb 03 '12 at 10:30

1 Answers1

1

And ObservableCollection only listens to changes in the collection itself. It is not responsible for listening to changes made to items inside the collection. If you want that behavior, you'll have to add it yourself.

Usually I add something to the CollectionChanged event, which adds/removes PropertyChanged events to the items in the collection.

void MyCollection_CollectionChanged(object sender, CollectionChangedEventArgs e)
{
    if (e.NewItems != null)
    {
        for each (SomeObject item in e.NewItems)
            item.PropertyChanged += SomeObject_PropertyChanged;
    }

    if (e.OldItems != null)
    {
        for each (SomeObject item in e.OldItems)
            item.PropertyChanged -= SomeObject_PropertyChanged;
    }
}

void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs e)
{

    // Handle event however you want here

    // For example, simply raise property change to refresh collection
    RaisePropertyChanged("MyCollection");

    // Or move item to new collection if it's selected
    if (e.Property == "IsSelected")
    {
        var item = object as SomeItem;
        MyCollectionA.Remove(item);
        MyCollectionB.Add(item);
    }
}
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Thank you very much ... yes this seems the way to go. However, it will take quite some time to implement in my (non MVVM) app. Sorry it took so long for commenting, but I did not get an email notification. – Michel Keijzers Feb 06 '12 at 12:08