views:

46

answers:

1

I have two ObservableCollections, say ObservableCollection<Cat> and ObservableCollections<Dog>. Cat and Dog both derive from class Pet. I want to display a list of all Pets. How do I do this? I prefer not want create a new ObservableCollection<Pet> by adding items from the two source lists because this list will become stale as more Cats and Dogs are added to the source lists. I can think of two approaches:

1) Create a "Decorator" ObservableCollection that keeps the two source collections as members and iterates over them every time.

2) Create an ObservableCollection<Pet> that does have the combined elements of the two source collections, but is also dependent on the source collections. Thus if a Cat is added to the Cat collection, this collection is notified and it adds the new Cat to itself.

Is there a standard way to solve this issue? I don't want to reinvent the wheel!

+4  A: 

Use a CompositeCollection to aggregate multiple collections and items with full collection change support.

Edit: CompositeCollection isn't a dependency object so there no notion of data context, hence why the binding doesn't work. You have to create the collection from code behind if you add bound items or collections.

Julien Lebosquain
Excellent! Exactly what I was looking for. Thanks.
Naresh
Well, I have been trying to make CompositeCollection work for a few hours now, but can't get it to work. I am specifying it as the ItemSource to my ComboBox like this (Cats is an ObservableCollection in my ViewModel):<CompositeCollection> <CollectionContainer Collection="{Binding Cats}" /></CompositeCollection>But I get this error:Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Cats; DataItem=null; If I remove the CompositeCollection completely and bind straight to ObservableCollection then everything works. Any clues?
Naresh