I have a class like so:
Class A
{
public ObservableCollection<T> collectionA;
public ObservableCollection<T> collectionB;
public T objectA;
}
I want to expose another property:
public ObservableCollection<T> All;
that contains all of collectionA, collectionB and objectA.
Initially, I saw other questions that pointed me towards the CompositeCollection class. However, if I do that, it appears that whenever I change collectionA, the changes to it do not cause an event to propagate through the CompositeCollection and notify things that it is bound to (Some of those things, are actually my own classes).
So, my second approach was a quick and dirty function:
public void HookCollection(ObservableCollection<T> dest, ObservableCollection<T> source)
source.CollectionChanged += new NotifyCollectionChangedEventHandler(delegate(object sender, NotifyCollectionChangedEventArgs e)
{
// Apply the same changes to the destination collection
if (e.Action == NotifyCollectionChangedAction.Reset)
{
foreach (T o in source)
{
dest.Remove(o);
}
}
if (e.NewItems != null)
{
foreach (T o in e.NewItems)
{
dest.Add(o);
}
}
if (e.OldItems != null)
{
foreach (T o in e.OldItems)
{
dest.Remove(o);
}
}
});
}
But I quickly found that in the "Reset" action, the items that were originally inside the source collection have already been destroyed, so I don't know what to remove from the destination ones.
This property is bound to a control that has some properties on it that are dependent upon the contents of this list, ie... Minimum and Maximum values of the entire set. These are in turn bound to the control. So being able to iterate over it as an IEnumerable would be very useful (and CompositeCollection makes this difficult).
As such, I need to have a clean way of being notified of changes to the list (and the sub lists).
At the moment, the only solution I can see is in my control class, detecting the CompositeCollection, then iterating over each CollectionContainer and attaching to it's CollectionChanging event if it has one. However, as you can imagine, this is a rather nasty way to hook into events. It'd be nice to have some way of aggregating those events cleanly. (I thought that was CompositeCollection but apparently not?).
Thanks for any thoughts you might have!