How to display two ObservableCollections as one list in WPF?

I have two ObservableCollections, say ObservableCollection<Cat> and ObservableCollections<Dog> . The cat and dog come from the Pet class. I want to display a list of all pets. How can I do it? I prefer not to create a new ObservableCollection<Pet> by adding items from two source lists, because this list will become obsolete as more cats and dogs are added to the original lists. I can imagine two approaches:

1) Create a โ€œDecoratorโ€ ObservableCollection that stores the two source collections as members and iterates over them each time.

2) Create an ObservableCollection<Pet> that has the combined elements of the two source collections, but also depends on the source collections. Thus, if Cat is added to the Cat collection, this collection will be notified and will add the new Cat to itself.

Is there a standard way to solve this problem? I do not want to reinvent the wheel!

+4
source share
1 answer

Use CompositeCollection to aggregate multiple collections and items with full support for modifying the collection.

Edit : CompositeCollection not a dependency object, so there is no concept of data context, so the binding does not work. You must create a collection from the code behind if you add related items or collections.

+7
source

Source: https://habr.com/ru/post/1313186/


All Articles