Repository navigation
InternalDesign1.en
I designed this library to make tree structures easier to work with and more flexible to define.
In the process, I also needed to define a number of supporting classes beyond the tree structures themselves.
The standard library did not provide sufficient support for tree-structure change notifications and collection-related functionality, so this library provides its own implementations.
- ITreeNode
- The TreeNodeBase Hierarchy
- The HierarchyWrapper Hierarchy
- Collections
- ObservedPropertyTree, Which Monitors Specified Properties

NodeIndex and NodePath are provided to indicate the position of an arbitrary node within a tree structure.
They can be obtained by using the GetNodeIndex() and GetNodePath() extension methods.

Derived types of TreeNodeBase and NAryTreeNode allow null to be added to their child-node collections.
Although null values are unnecessary during enumeration and can cause errors, prohibiting them would make it impossible to distinguish Left from Right in structures such as BinaryTree.
In addition, when an ITreeNode is a wrapper, cycles or duplicates in the source tree structure must be tolerated; otherwise, the wrapper cannot fulfill its intended role.
With these considerations in mind, the Traverse method is provided.
public static IEnumerable<T> Traverse<T>(
this ITreeNode<T> startNode,
Func<T, IEnumerable<T?>> getNodes,
Func<T, IEnumerable<T?>, IEnumerable<T?>, IEnumerable<T?>> updatePendingNodes)
where T : ITreeNode<T> {
}The second argument, getNodes, obtains a collection from a node. This function is applied only once to each node.
The third argument, updatePendingNodes, changes the order of pending nodes. A node is enumerated when the first element is not null and the node has already passed through getNodes. A node that has been enumerated is never enumerated again.
This makes it possible to ignore null values and avoid infinite loops.
The Traverse method is used by many other extension methods. Here are a few examples.
/// <summary>Generates a sequence in preorder starting from the current node.</summary>
public static IEnumerable<T> PreOrder<T>(this ITreeNode<T> self) where T : ITreeNode<T> {
return self.Traverse(a => a.Children, (a, b, c) => b.AddHead(a).Concat(c));
}
/// <summary>Generates a sequence in the ancestor direction starting from the current node, with the root as the last element.</summary>
public static IEnumerable<T> Upstream<T>(this ITreeNode<T> self) where T : ITreeNode<T> {
return self.Traverse(a => new T?[1] { a.Parent }, (a, b, c) => new T?[1] { a }.Concat(b).Concat(c));
}
/// <summary>Enumerates the leaf nodes in the descendant direction from the current node.</summary>
public static IEnumerable<T> Leafs<T>(this ITreeNode<T> self) where T : ITreeNode<T> {
return self.Traverse(a => a.Children, (a, b, c) => (b.OfType<T>().Any() ? b : new T?[1] { a }).Concat(c));
}TreeNodeBase implements only ITreeNode and is read-only.
Customize it by deriving from this class, defining public methods, and overriding virtual methods.
The collection used for internal operations is specified by SetupInnerChildCollection,
the collection exposed to external callers is specified by SetupPublicChildCollection,
and operations on the internal collection are performed by Core methods.
The add and remove methods defined by IMutableTreeNode have return values.
public interface IMutableTreeNode<TNode> : ITreeNode<TNode>
where TNode : IMutableTreeNode<TNode> {
/// <summary>Adds a child node.</summary>
/// <param name="child">The child node.</param>
/// <returns>The current node.</returns>
TNode AddChild(TNode child);
/// <summary>Adds a child node at the specified index.</summary>
/// <param name="index">The index.</param>
/// <param name="child">The child node.</param>
/// <returns>The current node.</returns>
TNode InsertChild(int index, TNode child);
/// <summary>Removes a child node.</summary>
/// <param name="child">The child node to remove.</param>
/// <returns>The removed node.</returns>
TNode RemoveChild(TNode child);
/// <summary>Removes all child nodes.</summary>
/// <returns>The removed nodes.</returns>
IReadOnlyList<TNode> ClearChildren();
}Assuming that an operation completes successfully, the return values are designed to provide convenient access to the child node being added or removed.
For an add method, the added node is easily accessible from the current node (the parent), so the current node is returned.
For a remove method, the removed child can no longer be accessed through the parent, so the removed child node is returned.
The Try methods behave in the same way when the operation succeeds. If it fails, the return values are reversed.
| Operation | Result | bool | Return value |
|---|---|---|---|
| Add | Added successfully | true |
Self |
| Already added | false |
child |
|
| Could not be added | false |
child |
|
| Remove | Removed successfully | true |
child |
| Node not found | false |
Self |
|
| Could not be removed | false |
Self |

ObservableGeneralTreeNode, which derives from GeneralTreeNode, allows subscribers to the StructureChanged event to receive notifications of additions, removals, and moves within the tree to which the node belongs, as viewed from that node. It also implements INotifyPropertyChanged, so changes to the parent node raise a notification for the Parent property.
A challenge in implementing this mechanism is that it is impossible to determine which notifications should be raised for which nodes until the operation has actually completed. An operation may simply add or remove a node, move it within the same tree, move it between siblings, or make multiple changes as part of a single operation.
Therefore, a mechanism was needed to ensure that an operation is executed only once at the end, even if it is invoked recursively or multiple times. In some cases, this mechanism also compares the state before and after the operation.
Register a key and its corresponding action in advance by using the Register method.
Before an operation, obtain an IDisposable by calling ExecuteUnique or LateEvaluate, and dispose of it after the operation. The registered action is executed when all the generated IDisposable instances have been disposed.
A simpler overload, ExecuteUnique(Action operation), is also available and does not require prior registration.
It does not require a key either; instead, operations are identified by the value of operation.Method.MetadataToken.
If a lambda expression is supplied, different values may be produced even for identical operations. Therefore, specify a method or a field variable of type Action. Also pay attention to the version from which the operation is specified.
This method remains because I needed it in an earlier application to defer UI updates.
It derives from UniqueOperationExecutor and defines the LateEvaluateTree method.
As shown below, the Core method compares the state before and after an operation.
ObservableGeneralTreeNode.cs
protected override void ShiftChildCore(int oldIndex, int newIndex,Action<IEnumerable<TNode>,int,int>? action = null) {
action ??= (collection, idx1, idx2) =>
((ObservableCollection<TNode>)collection).Move(idx1, idx2);
using (ChildNodes.ElementAt(oldIndex)?.UniqueExcutor.LateEvaluateTree()){
base.ShiftChildCore(oldIndex, newIndex,action);
}
}The OnStructureChanged method, a member of IObservableTreeNode, is hidden and used by this class when raising notifications.
The HierarchyWrapper family consists of classes intended to wrap other hierarchical or tree structures.

Since wrapping is their primary purpose, their implementation of Equals is distinctive.
Two wrappers are considered equal if their sources are the same. If both sources are null, however, the wrappers themselves are compared for identity.
This makes it possible to handle cyclic source structures and multiple null branches in a source structure, as can occur with NAryTreeNode.
The child-wrapper collection is lazily evaluated: it is created or reevaluated when accessed.
The main difference between HierarchyWrapper and BindableHierarcyWrapper is that
the former does not immediately reflect changes, even if the source child-node collection implements INotifyCollectionChanged (changes are reflected when accessed),
whereas the latter reflects changes immediately. The HierarchyWrapper class deliberately wraps the source in a read-only collection.
HierarchyWrapper.cs
private protected virtual IEnumerable<TSrc>? getSourceChildren {
get {
var src = this.SourceChildren;
if (src is INotifyCollectionChanged) return src.AsReadOnly();
return src;
}
}private protected override IEnumerable<TSrc>? getSourceChildren
=> this.SourceChildren;This is because a subscription would need to be removed if the source child-node collection implemented INotifyCollectionChanged.
I reasoned that if synchronization is not required, there is no need to subscribe to events; in fact, automatic synchronization could make the wrapper less convenient to use.
If you want to preserve the current tree structure without continuous synchronization, use the Convert() extension method.
If you want the tree structure at the time of each access to be reproduced, I recommend creating a class derived from HierarchyWrapper, or using the AsValuedTreeNode() extension method (which uses the lightweight wrapper class ReadonlyValuedTreeNode).
If you need to unsubscribe from the source during Dispose, or always keep the wrapper synchronized with the source structure, derive from BindableHierarchyWrapper.
As mentioned above, the child-wrapper collection is lazily evaluated and initialized when accessed.
If Dispose is called before the collection has ever been accessed, it is initialized in an empty, unsynchronized state and then disposed. Consequently, child wrappers for the collection elements are not initialized.
Internally, the accessing node (an ancestor or the node itself) sets the private protected bool IsImitating property of the accessed node (the node itself or a descendant) to false before traversing it.
private CombinableMirroredChildrenCollection<TWrpr>? _wrappers;
private protected CombinableMirroredChildrenCollection<TWrpr> InnerChildNodes {
get {
if(_wrappers is null) {
var srccn = getSourceChildren;// Source child nodes
_wrappers = new CombinableMirroredChildrenCollection<TWrpr>(
// Convert source child nodes to wrapper child nodes, and
// initialize ImitableCollection using the value indicating whether synchronization is currently enabled.
(srccn ?? new ObservableCollection<TSrc>())
.ToImitable(GenerateChild, null, IsImitating),
// The value reflected in the SourceChildrenIsObservable property by the Children property getter.
srccn is INotifyCollectionChanged,
// Callback when a child-node wrapper is added.
SetupChildNode,
// Callback when a child-node wrapper is removed.
HandleRemovedChildNode);
}
return _wrappers;
}
}
private IEnumerable<TWrpr>? _children;
public IEnumerable<TWrpr> Children {
get {
_children ??= SetupPublicChildCollection(InnerChildNodes);
if (this.IsImitating && !InnerChildNodes.SourceChildrenIsObservable) {
// Force the changes to be reflected.
InnerChildNodes.Imitate();
}
return _children;
}
}
protected virtual IEnumerable<TWrpr> SetupPublicChildCollection(CombinableMirroredChildrenCollection<TWrpr> children)
=> children;protected virtual void Dispose(bool disposing) {
if (disposing) {
var nd = this
.Traverse(a => {
// If the wrapper collection is initialized during this traversal, initialize it in an empty, unsynchronized state.
a.IsImitating = false;
return a.InnerChildNodes;
}, (a, b, c) => c.AddHead(a).Concat(b))
.Skip(1).Reverse().OfType<IDisposable>();
foreach (var n in nd) n.Dispose();
InnerChildNodes.Dispose();
}
isDisposed = true;
}As shown in the source code above, accessing the Children property calls InnerChildNodes.Imitate() to force synchronization. This is why the child-node collection of HierarchyWrapper is updated when accessed.
The same behavior applies to BindableHierarcyWrapper when the source child-node collection does not implement INotifyCollectionChanged.
To support synchronization, the HandleRemoveChild method is also provided as an extension point for handling the removal of wrappers.
In BindableHierarchyWrapper, when a child wrapper is removed, its Dispose method is called through HandleRemoveChild.
If you want to keep using a wrapper after it has been removed, you can intercept the removal here.
You can also retain wrappers in a cache by overriding HandleRemoveChild. To reuse them, override GenerateChild as well. (If the source contains null, you may need to take care when managing null wrappers and preventing duplicate wrappers for descendant nodes.)
Overriding SetupPublicChildCollection to customize the child-wrapper collection can change how wrappers are handled. This is discussed later.
Since wrapping is the primary purpose, these classes are likely to be used as ViewModels. In such cases, you may want to add specific elements at the beginning or end independently of the collection in the hierarchical Model, or control the order and visibility of elements.
Collections that meet these requirements are defined in the Collections namespace.
The requirements are summarized below.
Requirements essential to the implementation are marked as mandatory, while those intended to improve customizability are marked as supplementary.
| No. | Type | Description | Notes / Examples |
|---|---|---|---|
| 1 | Mandatory | Convert each element in the source collection and keep the result synchronized | |
| 2 | Mandatory | Support Dispose on the collection (unsubscribe from notifications) |
|
| 3 | Mandatory | Allow synchronization with the source collection to be enabled or disabled | Reevaluation on access; supports initialization during Dispose due to lazy evaluation. |
| 4 | Mandatory | Allow callbacks when elements are added or removed | Configure child elements on addition and call Dispose on removal. |
| 5 | Supplementary | Allow observable collections to be combined | Configure fixed nodes. |
| 6 | Supplementary | Allow sorting and filtering of synchronized collections | To improve customizability as a ViewModel. |

The classes can be broadly divided into three groups:
-
ImitableCollection, which allows synchronization to be controlled -
ObservableMirrorCollectionand its derived classes, which handle synchronization -
PropertyTrackingCollection, which monitors the properties of each element
These are the three groups.
The resulting collections are CombinableMirroredChildrenCollection and ObservableFilterSortMirrorCollection.
It can be obtained by using the ToImitable extension method.
In most cases, it is used as ImitableCollection<TDst>, which takes one type argument.
The non-generic class defines abstract members for controlling the suspension and resumption of synchronization, leaving their implementation to derived classes.
Within this library, only Imitate() and Dispose() are used, but the Pause and ClearAndPause methods are also provided to suspend synchronization for general-purpose use.
The abstract members are implemented by ImitableCollection<TSrc, TDst>. Synchronization itself is handled by the nested SDPairCollection class, which derives from ObservableMirrorCollection described below.
If false is passed to the isImitate argument of ToImitable, the IsImitating property becomes false, and the collection is initialized in an empty, unsynchronized state.
Both Pause() and ClearAndPause() stop synchronization and unsubscribe from the source collection. However, ClearAndPause() also removes all elements, so the removedAction supplied during initialization is invoked.
ImitableCollection<TDst> satisfies mandatory requirements 2 and 3.
This library contains two implementations of reordering logic.
The first is the ApplyCollectionChange method in ObservableMirrorCollection. It performs the corresponding operations in response to the subscribed CollectionChanged event.
During this process, a conversion function is invoked before adding an item, and a removal callback is invoked after removal. Even when a collection Reset notification is raised by the Clear method, the removal callback is invoked for each element.
ObservableMirrorCollection.ApplyCollectionChanged( ) #L82
protected virtual void ApplyCollectionChange(NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
for (int i = 0; i < e.NewItems?.Count; i++) {
var newItem = (T?)e.NewItems[i];
int insertIndex = e.NewStartingIndex >= 0 ? e.NewStartingIndex + i : Items.Count;
Items.Insert(insertIndex, _converter(newItem));
}
break;
case NotifyCollectionChangedAction.Remove:
// ( ... )
case NotifyCollectionChangedAction.Reset:
var lst = _removedHandler != null ? Items.ToArray() : Array.Empty<U>();
Items.Clear();
foreach (var rm in lst)
_removedHandler?.Invoke(rm);
break;
default:
throw new NotSupportedException($"Unknown collection change action: {e.Action}");
}
}The second is the AlignBy method of the ListAligner class. It is initialized with an editable list and operation delegates, then rearranges the entire list to match the order of the collection passed to AlignBy.
ListAligner.AlignBy #L86
public void AlignBy(IEnumerable<S> order) {
if (!order.Any() && 0 < _editList.Count) { _clear(); return; }
var orders = order.ToListScroller();
orders.MoveForEach(odrCurItm => {
if (_editList.Skip(orders.CurrentIndex).Any(a => _equality(odrCurItm, a))) {// If an element matching odrCurItm exists in the unedited portion of editList.
// An element matching odrCurItm is already at the current index.
if (_equality(odrCurItm, _editList[orders.CurrentIndex])) return;
// If the element at the current index is included in orders.
if (orders.HasNext(a => _equality(a, _editList[orders.CurrentIndex]))) {
// ( ... )
_remove(orders.CurrentIndex);
}
// Get the index of the element matching odrCurItm in the unedited portion of editList.
var tgt = _editList.Skip(orders.CurrentIndex).Select((v, i) => new { v, i }).First(x => _equality(odrCurItm, x.v)).i + orders.CurrentIndex;
_move(tgt, orders.CurrentIndex);
} else {// If no element matching odrCurItm exists in the unedited portion of editList.
if (_editList.Count <= orders.CurrentIndex || orders.HasNext(a => _equality(a, _editList[orders.CurrentIndex]))) {
_insert(orders.CurrentIndex, _convert(odrCurItm));// The index is beyond the end of editList, or the element currently at this index belongs later in the order.
} else {
_replace(orders.CurrentIndex, _convert(odrCurItm));
}
}
});
for (int i = _editList.Count - 1; orders.Items.Count <= i; i--) { _remove(i); }
}If multiple identical elements are present, their relative order is not guaranteed, so this is an unstable sort. It is also an in-place sort because it operates on a previously supplied editable collection.
ObservableMirrorCollection<T,U> is a collection of U synchronized with a source collection of T. It requires a conversion from T to U and a way to compare the identity of T and U elements. It subscribes to change notifications from the source collection in its constructor and rearranges the entire collection by calling AlignBy.
One somewhat unusual design choice is that the property representing the source collection is virtual.
protected virtual IEnumerable<T> SourceItems { get; }
In C#, if a derived class overrides this property, calling it from the base-class constructor returns null; consequently, no subscription or reordering takes place.
This behavior is useful when synchronization is not necessarily enabled during initialization, as in SDPairCollection. The observable, combinable collection ObservableCombinableCollection, described below, also overrides this property.
The standard library ReadOnlyObservableCollection does not provide a way to unsubscribe from the observed collection, so its lifetime depends on that of the observed collection. If it has a shorter lifetime, this can result in a memory leak. To avoid this, this class implements IDisposable.
ObservableMirrorCollection<T,U> satisfies mandatory requirements 1, 2, and 4.
ObservableMirrorCollection<T,U> is the base class of ObservableMirrorCollection<T>, which sets the default EqualityComparer.
public class ObservableMirrorCollection<T>:ObservableMirrorCollection<T, T> {
public ObservableMirrorCollection(
IEnumerable<T> source, Action<T>?
addingAction = null,
Action<T>? removedAction = null,
IEqualityComparer<T>? equality = null)
: base(source,
addingAction is null ? (x => x) : (x => {addingAction.Invoke(x); return x; }),
(x, y) => equality?.Equals(x, y) ?? Equality<T>.ValueOrReference.Equals(x, y),
removedAction) {
}
}The comparison checks for identity as strictly as possible.
Even if the original type defines value equality through IEquatable or a similar mechanism, the following rules are used to reproduce the order as faithfully as possible.
Both are null => true
Both are value types of the same type and have equal values => true
Both are reference types and refer to the same instance => true
Otherwise => false
ObservableCombinableCollection and ObservableFilterSortMirrorCollection both derive from ObservableMirrorCollection<T>.
Collections that implement INotifyCollectionChanged can be combined. Collections that do not implement it can also be added, but their changes will not be reflected.
Overriding the SourceItems property disables the base-class constructor logic.
When a collection is added, it is first wrapped in an unsynchronized ImitableCollection. The wrapper is subscribed to, and stored in an internal variable. Finally, synchronization is enabled so that collection change notifications are received and reflected.
ObservableCombinableCollection.cs
bool attach(int index, IEnumerable<T> collection) {
ThrowExceptionIfDisposed();
if (_combines.Any(x => x.Item1 == collection)) return false;
// Create an ImitableCollection from the key IEnumerable.
var imit = collection.ToImitable(x => x, null, false);
// Subscribe to events from imit.
var lsnr = new EventListener<NotifyCollectionChangedEventHandler>(
h => ((INotifyCollectionChanged)imit).CollectionChanged +=h,
h=> ((INotifyCollectionChanged)imit).CollectionChanged -=h,
(s, e) => changedAction(s,e));
// Callback when the collection is detached.
var dsp = new DisposableObject(() => {
imit.Dispose();
lsnr.Dispose();
});
// Add the key IEnumerable, imit, and the detach action (IDisposable) together.
_combines.Insert(index, new Tuple<IEnumerable, ImitableCollection<T>, IDisposable>(collection, imit, dsp));
imit.Imitate();// Reflect the newly added collection.
return true;
}This satisfies supplementary requirement 5.
CombinableMirroredChildrenCollection, which handles the child-node collection in HierarchyWrapper, derives from ObservableCombinableCollection.
Its base class satisfies mandatory requirements 1, 2, and 4. It is initialized with an ImitableCollection that reflects the child-node collection and satisfies mandatory requirements 2 and 3.
The initialization method of CombinableMirroredChildrenCollection specifies the addition callback (setting Parent) and removal callback (clearing Parent and calling HandleRemovedChild).
The Dispose operation is also assigned directly to the Dispose method of CombinableMirroredChildrenCollection.
With this design, overriding SetupPublicChildCollection allows combined and uncombined elements in the children argument to be handled differently. (In fact, this desired behavior was the reason ChildCollection derives from CombinableCollection rather than MirrorCollection.)
Here is an example.
Override SetupPublicChildCollection in a wrapper node derived from BindableHierarchyWrapper to customize the collection exposed to external callers.
ObservableCollection<SampleWrapper> dummyNodes = new();
ObservableCollection<SampleWrapper> optionNodes = new();
// children: the source child-node collection, supplied in a combinable state.
protected override IEnumerable<SampleWrapper> SetupPublicChildCollection(CombinableMirroredChildrenCollection<SampleWrapper> children){
// Combine dummyNodes with children.
children.AppendCollection(dummyNodes);
//children : [child1,child2,...,dummy1,dummy2,...]
// Create elementList by filtering the combined children.
var elementList = children.ToReadOnlyObservableFilterSort();
elementList.FilterBy(x=>x.Status.IsActive);
//elementList : [child1,child4,...,dummy2,dummy5,...]
// Create a new combinable collection, displayList, and combine optionNodes with elementList.
var displayList = new ObservableCombinableCollection();
displayList.AppendCollection(optionNodes);
displayList.AppendCollection(elementList);
//displayList : [opt1,opt2,...,child1,child4,...,dummy2,dummy5,...]
return displayList;
}In the code above, dummyNodes are incorporated as child nodes and treated just like other children, whereas optionNodes are not incorporated.
Elements excluded by the filter (child2, child3, dummy1, dummy3, ...) retain their parent, but are not enumerated as children from the parent’s perspective (they are not included in the ITreeNode.Children property). They remain internal children, however, so callbacks associated with additions and removals from the synchronized source child collection, as well as processing during this node’s Dispose, are still performed.
The elements opt1 and opt2 are included in the Children property and are therefore enumerated as children externally. However, callbacks associated with additions and removals from the optionNodes collection, as well as processing during this node’s Dispose, are not performed.
The intended use cases are:
- dummyNodes: Temporary elements that have not yet been saved or have not undergone a particular operation. For reasons related to the processing workflow, they appear to belong to the tree but are not actually part of it internally.
- optionNodes: Elements such as status indicators or menus for adding new items. They are included in the tree for visual purposes.
This is the distinction I have in mind when using these collections.
As an additional note, let us consider whether optionNodes can be made to undergo the same processing.
First, setting the Parent property is not possible because the method that sets it is not accessible.
For removal processing, adding the following line calls HandleRemovedChild and allows the elements to be handled in the same way as the others.
ObservableCollection<SampleWrapper> dummyNodes = new();
ObservableCollection<SampleWrapper> optionNodes = new();
protected override IEnumerable<SampleWrapper> SetupPublicChildCollection(CombinableMirroredChildrenCollection<SampleWrapper> children){
children.AppendCollection(dummyNodes);
var elementList = children.ToReadOnlyObservable();
elementList.FilterBy(x=>x.Status.IsActive);
var displayList = new ObservableCombinableCollection();
displayList.AppendCollection(optionNodes);
displayList.AppendCollection(elementList);
// Add the following line.
optionNodes.AddRemoveObserver().Removed(x => this.HandleRemoveChild(x));
return displayList;
}To handle disposal when this node is disposed, override the Dispose method and add the required processing.
protected override void Dispose(bool disposing){
if(disposing){
foreach(var opt in optionNodes.OfType<IDisposable>()) opt.Dispose();
}
base.Dispose(disposing);
}Taking these points into account, the result is as follows.
| Collection | Set / clear Parent
|
Traversal | On removal | On Dispose
|
|---|---|---|---|---|
| child1, child2, ... | Yes | Ancestor and descendant traversal works correctly | Yes | Yes |
| dummy1, dummy2, ... | Yes | Ancestor and descendant traversal works correctly | Yes | Yes |
| opt1, opt2, ... | No | Descendant traversal only; null in the ancestor direction |
No (can be handled) | No (can be handled) |
This collection extends ObservableMirrorCollection with filtering and sorting. You can specify element properties, and filtering or sorting is applied immediately when their values change.
If the element’s property values also implement INotifyPropertyChanged, nested properties can be specified.
//Collection of active elements only
list.FilterProperty(x => x.Option.IsActive);//Collection of active elements with points less than 30
list.FilterBy(x => x.Point < 30 && x.Option.IsActive, x=>x.Point, x=>x.Option.IsActive);Wrapping a collection with this class satisfies supplementary requirement 6.
To implement ObservableFilterSortMirrorCollection, the following capabilities are required:
- Subscribe to and unsubscribe from property-change notifications as collection elements are added and removed.
- Allow nested properties to be specified when property values implement
INotifyPropertyChanged. - Identify the name of the property that changed.
These are the required capabilities.
PropertyTrackingCollection provides the first capability.
The second and third capabilities are provided by instances of ObservedPropertyTree (described below).
The implementation mainly uses the following fields.
// Instances that observe each element in the collection synchronized with the target collection.
ObservableMirrorCollection<T, ObservedPropertyTree<T>> _trees;
// Dimension 1: a list.
// Dimension 2: a dictionary keyed by property name.
// Dimension 3: a dictionary keyed by the observing instance, with the property-change unsubscription action as its value.
List<
Dictionary<
string,
Dictionary<
ObservedPropertyTree<T>,
IDisposable>>> _trackingDics;The trackingDics variable grows in three dimensions: the first when a new tracking list is added, the second when a property to observe is added to that list, and the third when an item is added to the target collection.
Addition in the first dimension (creating a TrackingPropertyList) is handled by the CreateTrackingList method.
public TrackingPropertyList<T> CreateTrackingList() {
var dic = new Dictionary<string, Dictionary<ObservedPropertyTree<T>, IDisposable>>();
_trackingDics.Add(dic);
return new TrackingPropertyList<T>(this, dic, addExpressions, removeExpressions, clearExpressions, dispExpressions);
}Adding and removing observed properties in the second dimension is provided through TrackingPropertyList<T>.
void addExpressions(Dictionary<string, Dictionary<ObservedPropertyTree<T>, IDisposable>> exprDic, IEnumerable<Expression<Func<T, object>>> exps) {
ThrowExceptionIfDisposed();
foreach (var key in exps) {
string keyname = string.Join(".", PropertyUtils.GetPropertyPath(key));
if (exprDic.ContainsKey(keyname)) continue;
var optrees = new Dictionary<ObservedPropertyTree<T>, IDisposable>();
foreach (var trr in _trees) {
// For each property name added in the second dimension,
// add the observer for the corresponding collection item and its unsubscription action in the third dimension.
optrees.Add(trr, trr.Subscribe(key, this.handleItemPropertyChanged));
}
exprDic[keyname] = optrees;
}
}Operations in the third dimension are performed by the trees variable, which responds to changes in the target collection and invokes callbacks when items are added or removed.
_trees = new ObservableMirrorCollection<T, ObservedPropertyTree<T>>(
items,
addedItem => {// Callback when an item is added.
var opt = new ObservedPropertyTree<T>(addedItem);
foreach (var exprDic in _trackingDics) {
foreach (var expr in exprDic.Keys) {
// Add an entry in the third dimension for every tracking list and observed property.
var sbsc = opt.Subscribe(PropertyUtils.CreatePropertyExpression<T>(expr), handleItemPropertyChanged);
exprDic[expr][opt] = sbsc;
}
}
return opt;
},
(itm, tree) => Equality.ValueOrReference.Equals(itm, tree.Root.Source),
removedOpt => {// Callback when an item is removed.
foreach (var exprDic in _trackingDics) {
foreach (var expr in exprDic.Keys) {
// Remove the third-dimension entry for every tracking list and observed property.
ResultWith<IDisposable>.Of(exprDic[expr].Remove, removedOpt).When(o => o.Dispose());
}
}
removedOpt.Dispose();
}
);Implementing PropertyTrackingCollection requires monitoring specified properties, including nested properties.
ObservedPropertyTree was defined for this purpose.

It subscribes to property-change notifications on the target instance. If a property value implements INotifyPropertyChanged, it can subscribe to that property in turn, and so on.
A PropertyChainNode is created for each observed property and added or removed as property-change notifications are subscribed to or unsubscribed from.
Its functionality is similar to the ObserveProperty method in the ReactiveProperty library.
That method could serve as an alternative to this class, but I do not intend to remove the class because I want to minimize dependencies on other libraries.
The differences from the ObserveProperty method are as follows:
- It can retrieve each property name along the path to the property that changed.
- It can retrieve the names and values of the properties currently being observed.
- When observing multiple nested properties from a source object, it shares listeners for common ancestor properties.
- It can replace the source object.
NotifyObject was created to make it easier to use alongside the ReactiveProperty library. However, since nested properties can be specified with ObserveProperty, I now think it is unnecessary. I had overlooked that capability. I am considering removing it.