INotifyCollectionChanged with collections of collections

This is a repost

I’ve been struggling with consuming the INotifyCollectionChanged and INotifyPropertyChanged events in my code.  They were obviously doing their thing because the UI was updating to interaction changes.
It turned out to be a mix of not having Two-Way binding enabled and how I had set up my collection.
The data binding was hiding the issue I had with the collection, so thanks to Valentin Iliescu and Yves Dolce for helping me sort that out.
It would appear that you have to wrap your sub collections in a class, rather than just declaring an ObservableCollection<T> and adding the event handler directly.

So you have to do this

public class MyCollection : ObservableCollection<MyType>

{

  public MyCollection()

  {

this.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);

  }

}

public class EnclosingType

{

  private MyCollection myCollection;

public EnclosingType ()
  {
    myCollection = new MyCollection ();
  }
}

Rather than doing this in your enclosing type

public class EnclosingType

{

  private ObservableCollection< MyType>() myCollection;

public EnclosingType ()
  {
    myCollection = new ObservableCollection< MyType>();
    myCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);
  }
}

This doesn’t seem the correct behaviour and I’d appreciate anyone’s comment on it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: