CombinableObservableCollection - Houzkin/TreeStructures GitHub Wiki

CombinableObservableCollection

A class designed to combine collections implementing INotifyCollectionChanged.
It can combine collections even if they do not implement INotifyCollectionChanged, but in such cases, collection change notifications are issued when a new collection is combined or removed.

public class CombinableObservableCollection<T> : ReadOnlyObservableCollection<T>{

    //constractor
    public CombinableObservableCollection(IEqualityComparer<T>? comparer = null);

    public void AppendCollection(IEnumerable<T> collection);

    public void InsertCollection(int idx, IEnumerable<T> collection);

    public void RemoveCollection(IEnumerable<T> collection);

    public void ClearCollection();

    public ReadOnlyObservableCollection<T> AsReadOnlyObservableCollection();
}

Sample

var obs1 = new ObservableCollection<string>();
var obs2 = new ObservableCollection<string>("abc".Select(x=>x.ToString()));
var lst3 = new List<string>("123".Select(x=>x.ToString()));
var obs4 = new ObservableCollection<string>("qwerty".Select(x => x.ToString()));

var cmb = new ObservableCombinableCollection<string>();
(cmb as INotifyCollectionChanged).CollectionChanged += (s, e) => {
    Console.WriteLine($"action:{e.Action}, StartIndex:{e.NewStartingIndex}, NewItems:{string.Join(" ",e.NewItems?.OfType<string>() ?? Array.Empty<string>())}, OldIndex:{e.OldStartingIndex}, OldItems:{string.Join(" ",e.OldItems?.OfType<string>() ?? Array.Empty<string>())}");
};
cmb.AppendCollection(obs1);
cmb.AppendCollection(obs2);
cmb.AppendCollection(lst3);
cmb.AppendCollection(obs4);

Console.WriteLine(string.Join(", ", cmb));
//a, b, c, 1, 2, 3, q, w, e, r, t, y

obs1.Add("A");
Console.WriteLine(string.Join(", ", cmb));
//A, a, b, c, 1, 2, 3, q, w, e, r, t, y

obs2.Remove("b");
Console.WriteLine(string.Join(", ", cmb));
//A, a, c, 1, 2, 3, q, w, e, r, t, y

lst3.Add("100");
Console.WriteLine(string.Join(", ", cmb));
//A, a, c, 1, 2, 3, q, w, e, r, t, y

obs4[1] = "D";
Console.WriteLine(string.Join(", ", cmb));
//A, a, c, 1, 2, 3, q, D, e, r, t, y

obs4.Move(4, 0);
Console.WriteLine(string.Join(", ", cmb));
//A, a, c, 1, 2, 3, t, q, D, e, r, y

cmb.RemoveCollection(obs4);
Console.WriteLine(string.Join(", ", cmb));
//A, a, c, 1, 2, 3

cmb.InsertCollection(1, obs4);
Console.WriteLine(string.Join(", ", cmb));
//A, t, q, D, e, r, y, a, c, 1, 2, 3

cmb.RemoveCollection(lst3);
Console.WriteLine(string.Join(", ", cmb));
//A, t, q, D, e, r, y, a, c

cmb.InsertCollection(0, lst3);
Console.WriteLine(string.Join(", ", cmb));
//1, 2, 3, 100, A, t, q, D, e, r, y, a, c

cmb.Dispose();
Console.WriteLine(string.Join(", ", cmb));
// (empty)

The SetupPublicChildCollection method of HierarchyWrapper takes as its argument a class that inherits from this class, namely, CombinableChildWrapperCollection.

⚠️ **GitHub.com Fallback** ⚠️