ObservableCollection in WPF is a very commonly used collection object. We can bind it to a collection control such as ListBox, and when the collection changes, it will be updated to the interface synchronously. However, sometimes we need to merge two sets and display them on the interface. What should we do at this time?
At first glance, this is a very simple thing. .Net's BCL itself provides the IEnumerate collection connection function - Concat, through which two collections can be easily connected. But when you use it to connect the collection and render it to the interface, you will find a problem - although it can splice the current results and display it, it will not synchronize the changes to the collection.
The reason is very simple: the reason why the interface can synchronize the result of ObservableCollection is because it implements the INotifyCollectionChanged interface. However, the new collection connected with Concat does not implement this interface. Although it is not difficult to implement such a merged notification collection, .Net itself provides such a collection-CompositeCollection, I won’t repeat the wheel here. The code example is as follows:
void testCompositeCollection() { var cmpc = new CompositeCollection(); var numbers = new ObservableCollection<int>(); var lines = new ObservableCollection<string>(); (new CollectionContainer() { Collection = numbers }); (new CollectionContainer() { Collection = lines }); = cmpc; foo(numbers); foo(lines); } async void foo(ObservableCollection<string> lines) { for (int i = 0; i < 10; i++) { await (800); ("Line " + 2 * i); } } async void foo(ObservableCollection<int> numbers) { for (int i = 0; i < 10; i++) { await (1000); (i); } }
This is all about this article about WPF merge ObservableCollection. I hope it will be helpful to everyone's learning and I hope everyone will support me more.