views:

410

answers:

2

Hello,

I've a ObserableCollection with Items in it, which implement the INotifyPropertyChanged Interface. This is how I create it:

        var myCollection = new ObservableCollection<MyViewModel>();
        myCollection.CollectionChanged += OnCollectionChanged;

_

        private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                if (e.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (ViewModelBase item in e.NewItems)
                    {
                        item.PropertyChanged -= myViewModelPropertyChanged;
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (ViewModelBase item in e.NewItems)
                    {
                        item.PropertyChanged += myViewModelPropertyChanged;
                    }
                }
            }
        }

Now my question is, doI need to loop trough all items and remove the "myViewModelPropertyChanged" before doing another

myCollection = new ObservableCollection<MyViewModel>();

or does this happen automatically? What about a myCollection.Clear();

Thanks for any input.

Cheers Joseph

A: 

I think that a myCollection.Clear(); or create a new myCollection over the old one won't unlink the objects of your collection of the event, and then I would do the iteration

Mike
+2  A: 

If I understand correctly, you have a Collection of objects. For each object, you have subscribed to some member events. Now your object has a reference to your handler functions.

When you clear the collection, if no one else references the member objects, you don't need to unsubscribe explicitly. The objects will get garbage collected.
The problem occurs when the publisher outlives the subscriber, in which case it keeps the subscriber alive due to the event handler/delegate references. e.g. if you store the publisher in a static field, if you don't unsubscribe explicitly - the subscriber will not be collected by the GC.

See also: 1198076 and other related questions.

Gishu