我返工@ GazTheDestroyer的回答到這個(需要C#7):
internal sealed class CompositeObservableCollection<T> : ObservableCollection<T>
{
public CompositeObservableCollection(INotifyCollectionChanged subCollection1, INotifyCollectionChanged subCollection2)
{
AddItems((IEnumerable<T>)subCollection1);
AddItems((IEnumerable<T>)subCollection2);
subCollection1.CollectionChanged += OnSubCollectionChanged;
subCollection2.CollectionChanged += OnSubCollectionChanged;
void OnSubCollectionChanged(object source, NotifyCollectionChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
AddItems(args.NewItems.Cast<T>());
break;
case NotifyCollectionChangedAction.Remove:
RemoveItems(args.OldItems.Cast<T>());
break;
case NotifyCollectionChangedAction.Reset:
Clear();
AddItems((IEnumerable<T>)subCollection1);
AddItems((IEnumerable<T>)subCollection2);
break;
case NotifyCollectionChangedAction.Replace:
RemoveItems(args.OldItems.Cast<T>());
AddItems(args.NewItems.Cast<T>());
break;
case NotifyCollectionChangedAction.Move:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException();
}
}
void AddItems(IEnumerable<T> items)
{
foreach (var me in items)
Add(me);
}
void RemoveItems(IEnumerable<T> items)
{
foreach (var me in items)
Remove(me);
}
}
}
請注意,您不能使用「CompositeCollectionView」進行分組。它的'CanGroup'是'false',它的'ICollectionView.GroupDescriptions'屬性是'null'並且是不可設置的。 –