I have 2 ObservableCollection<T>
objects. Let's call them A and B. I want to replicate the changes broadcasted by A (via INotifyCollectionChanged
) to B.
In other words, when A changes, B must replicate the same change:
- When A added an item, B must add the same item.
- When A moved an item, B must do the same move.
- And so on...
The problem comes with the complexity of NotifyCollectionChangedEventArgs
.
I'd like to avoid writing the code that checks for all operation combinations.
(add + remove + reset + move + replace) x (single-item + multi-item) - (invalid combinations)
My assumption (and hope) is that this logic already exists in .Net (I'm on .Net 6).
Here's some code that demonstrates my vision.
ObservableCollection<int> A = new ObservableCollection<int>();
ObservableCollection<int> B = new ObservableCollection<int>();
A.CollectionChanged += (s, args) =>
{
// This line doesn't build. It's just to show my intent.
B.Apply(args);
};
A.Add(1);
A.Add(2);
// At this point B should contain 1 and 2 because they were added to A.
Is there an existing .Net solution for this problem?
If the recipe doesn't exist, any pointers on how to properly implement it are appreciated.