Repository navigation
Tutorial4.en
These abstract classes wrap tree structures or other hierarchical structures (those that do not implement ITreeNode).
The source passed to the constructor becomes the root of the wrapper, and its descendants are wrapped recursively.
They maintain bidirectional parent-child references between wrappers and reproduce or customize the source structure.
These are the basic wrapper classes.
HierarchyWrapper is an abstract class for wrapping hierarchical structures.
TreeNodeWrapper is limited to tree structures that implement ITreeNode, so you do not need to override the SourceChildren property. There are no other differences.
HierarchyWrapper.cs
public abstract class HierarchyWrapper<TSrc,TWrpr>
: ITreeNode<TWrpr>, IEquatable<HierarchyWrapper<TSrc,TWrpr>>
where TSrc : class
where TWrpr : HierarchyWrapper<TSrc,TWrpr> {
protected HierarchyWrapper(TSrc source) { Source = source; }
#region ITreeNode interface
public TWrpr? Parent { get;}
public IEnumerable<TWrpr> Children { get; }
#endregion
protected TSrc Source { get; }
/// <summary>Specifies a reference to the source's child node collection.</summary>
protected abstract IEnumerable<TSrc>? SourceChildren { get; }
/// <summary>Conversion function applied to child nodes, converting from <typeparamref name="TSrc"/> to <typeparamref name="TWrpr"/>.</summary>
/// <param name="sourceChildNode">Child node to be wrapped</param>
/// <returns>Wrapped child node</returns>
protected abstract TWrpr GenerateChild(TSrc sourceChildNode);
/// <summary>Sets the collection to be exposed externally.</summary>
/// <param name="children">A combinable collection wrapping each node of <see cref="SourceChildren"/>.</param>
protected virtual IEnumerable<TWrpr> SetupPublicChildCollection(CombinableChildrenProxyCollection<TWrpr> children)
=> children;
/// <summary>Handles processing of a decomposed child node.</summary>
/// <remarks>This method is intended to be overridden in derived classes to add specific processing for an already decomposed child node.</remarks>
/// <param name="removedNode">Removed child node</param>
protected virtual void HandleRemovedChild(TWrpr removedNode) { }
}The roles of the methods are as follows:
-
SourceChildren: Gets the source's child node collection. -
GenerateChild: Creates the corresponding wrapper for a source child node. -
SetupPublicChildCollection: Customizes the wrapper's child node collection. -
HandleRemovedChild: Specifies what to do with the corresponding wrapper when a source child node is removed.
By default, HierarchyWrapper.Children returns IEnumerable, but the underlying instance is CombinableMirroredChildrenCollection, which inherits from ReadOnlyObservableCollection.
The following code defines NamedLayerWrapper, which wraps the NamedLayer class.
public class NamedLayerWrapper : HierarchyWrapper<NamedLayer, NamedLayerWrapper> {
public NamedLayerWrapper(NamedLayer source) : base(source) {
this.Name = "(" + source.Name + ")";
Console.WriteLine($"Create new {this.Name}");
}
protected override IEnumerable<NamedLayer>? SourceChildren => this.Source.ChildLayers;
protected override NamedLayerWrapper GenerateChild(NamedLayer sourceChildNode) {
return new NamedLayerWrapper(sourceChildNode);
}
protected override void HandleRemovedChild(NamedLayerWrapper removedNode) {
Console.WriteLine($"Removed {removedNode.Name}");
}
public string Name { get; }
}The Children property is initialized on first access. Subsequent accesses reflect any changes.
This behavior does not depend on whether the collection specified by SourceChildren implements INotifyCollectionChanged.
When changes are reflected in Children, HandleRemovedChild is called for each removed wrapper.
The following code shows when each node is initialized and removed.
var layers = "ABCDEF".ToCharArray()
.Select(x => x.ToString())
.ToDictionary(x => x, x => new NamedLayer() { Name = x });
var root = layers.Values.AssembleAsNAryTree(1, x => x, x => x.ChildLayers, (p, c) => p.ChildLayers.Add(c));
PrintHierarchy(root);
/*
└ A
└ B
└ C
└ D
└ E
└ F
*/
var wRoot = new NamedLayerWrapper(root);
// Create new (A)
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Print wrapper. ---
Create new (B)
Create new (C)
Create new (D)
Create new (E)
Create new (F)
(A)
└ (B)
└ (C)
└ (D)
└ (E)
└ (F)
*/
Console.WriteLine("--- Remove layer E. ---");
layers["D"].ChildLayers.Remove(layers["E"]);
Console.WriteLine("--- Add layer E to layer A. ---");
layers["A"].ChildLayers.Add(layers["E"]);
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Remove layer E. ---
--- Add layer E to layer A. ---
--- Print wrapper. ---
Create new (E)
Removed (E)
Create new (F)
(A)
├ (B)
│ └ (C)
│ └ (D)
└ (E)
└ (F)
*/The GenerateChild and HandleRemovedChild methods are called in the order in which the Children properties are accessed by ToTreeDiagram.
When a parent node changes, new wrappers are created for it and all its descendants.
When a node is moved between siblings as shown in the following code, its wrapper is moved as well.
Console.WriteLine("--- Remove layer E. ---");
layers["A"].ChildLayers.Remove(layers["E"]);
Console.WriteLine("--- Insert layer E to layer A at index 0. ---");
layers["A"].ChildLayers.Insert(0, layers["E"]);
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Remove layer E. ---
--- Insert layer E to layer A at index 0. ---
--- Print wrapper. ---
(A)
├ (E)
│ └ (F)
└ (B)
└ (C)
└ (D)
*/Wrapper creation and removal occur on demand and are not predictable. Subscribing to source events from these wrappers may therefore cause memory leaks.
If you need immediate updates to Children, change notifications, or resource cleanup through Dispose, derive from BindableHierarchyWrapper or BindableTreeNodeWrapper.
ReadOnlyValuedTreeNode, which can be used as a lightweight wrapper, also derives from HierarchyWrapper and therefore behaves in the same way.
ReadOnlyValuedTreeNode.cs
public sealed class ReadOnlyValuedTreeNode<TSrc,TVal>
: HierarchyWrapper<TSrc, ReadOnlyValuedTreeNode<TSrc,TVal>>
where TSrc : class {
/// <summary>Gets the value associated with the tree node.</summary>
public TVal Value { get; private set; }
}See also: Tutorial1 - Converting Between Tree Structures and Other Hierarchical Structures
These wrappers stay synchronized with the source child node collection and support disposal.
They implement INotifyPropertyChanged and are also intended for use as ViewModels in the MVVM pattern.
BindableHierarchyWrapper.cs
public abstract class BindableHierarchyWrapper<TSrc, TWrpr>
: HierarchyWrapper<TSrc, TWrpr>, INotifyPropertyChanged, IDisposable
where TSrc : class
where TWrpr : BindableHierarchyWrapper<TSrc, TWrpr> {
protected BindableHierarchyWrapper(TSrc source) : base(source) { }
/// <summary>Handles the removed child node.</summary>
/// <remarks>The base class calls the <see cref="Dispose()"/> method.</remarks>
/// <param name="removedNode">The removed child node.</param>
protected override void HandleRemovedChild(TWrpr removedNode)
=> removedNode.Dispose();
protected PropertyAccessor Properties { get; }
protected void ThrowExceptionIfDisposed() {...}
protected virtual void Dispose(bool disposing) {...}
public bool IsDisposed { get; }
}If the collection specified by SourceChildren implements INotifyCollectionChanged,
the Children property is initialized on first access, and subsequent collection changes are reflected immediately.
If it does not implement INotifyCollectionChanged, updates occur on access, as they do with HierarchyWrapper.
The HandleRemovedChild method disposes wrappers that have been detached.
As described below, wrappers that have already been disposed are not processed again by Dispose.
If you want to manage and reuse wrappers yourself, override this method and GenerateChild.
Define a wrapper node for the ObservableNamedNode class introduced earlier.
public class ReadOnlyLinkedNamedNode
: BindableTreeNodeWrapper<ObservableNamedNode, ReadOnlyLinkedNamedNode> {
public ReadOnlyLinkedNamedNode(ObservableNamedNode sourceNode) : base(sourceNode) {
this.Name = "{" + sourceNode.Name + "}";
Console.WriteLine($"Create new {this.Name}");
}
protected override ReadOnlyLinkedNamedNode GenerateChild(ObservableNamedNode sourceChildNode) {
return new ReadOnlyLinkedNamedNode(sourceChildNode);
}
protected override void HandleRemovedChild(ReadOnlyLinkedNamedNode removedNode) {
Console.WriteLine($"Removed {removedNode.Name}");
base.HandleRemovedChild(removedNode);
}
protected override void Dispose(bool disposing) {
Console.WriteLine($"{this.Name} is disposing");
//Console.WriteLine($"Start disposing {this.Name}.");
base.Dispose(disposing);
//Console.WriteLine($"Finished disposing {this.Name}.");
}
public string Name { get; }
}The following code shows when each node is initialized and removed.
var nodes = "ABCDEF".ToCharArray()
.Select(x => x.ToString())
.ToDictionary(x => x, x => new ObservableNamedNode() { Name = x });
var root = nodes.Values.AssembleAsNAryTree(1);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
└ B
└ C
└ D
└ E
└ F
*/
var wRoot = new ReadOnlyLinkedNamedNode(root);
// Create new {A}
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Print wrapper. ---
Create new {B}
Create new {C}
Create new {D}
Create new {E}
Create new {F}
{A}
└ {B}
└ {C}
└ {D}
└ {E}
└ {F}
*/
Console.WriteLine("--- Remove node E. ---");
nodes["D"].RemoveChild(nodes["E"]);
/*
--- Remove node E. ---
Removed {E}
{E} is disposing
{F} is disposing
*/
Console.WriteLine("--- Add node E to node A. ---");
nodes["A"].AddChild(nodes["E"]);
/*
--- Add node E to node A. ---
Create new {E}
*/
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Print wrapper. ---
Create new {F}
{A}
├ {B}
│ └ {C}
│ └ {D}
└ {E}
└ {F}
*/When node E is removed, the change is reflected immediately, and its wrapper and descendant wrappers are disposed.
When moving a node between siblings by removing it and then adding it again as shown below, a new wrapper instance is created.
Console.WriteLine("--- Remove node E. ---");
nodes["A"].RemoveChild(nodes["E"]);
/*
--- Remove node E. ---
Removed {E}
{E} is disposing
{F} is disposing
*/
Console.WriteLine("--- Insert node E to node A at index 0. ---");
nodes["A"].InsertChild(0, nodes["E"]);
/*
--- Insert node E to node A at index 0. ---
Create new {E}
*/
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Print wrapper. ---
Create new {F}
{A}
├ {E}
│ └ {F}
└ {B}
└ {C}
└ {D}
*/If the node is moved without being removed, its wrapper is simply moved as well.
Console.WriteLine("--- Move node E ---");
nodes["A"].MoveChild(0, 1);
/*
--- Move node E ---
*/
Console.WriteLine("--- Print wrapper. ---");
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
--- Print wrapper. ---
{A}
├ {B}
│ └ {C}
│ └ {D}
└ {E}
└ {F}
*/When a node wrapper is disposed, its descendant wrappers are disposed and detached in order from the leaves upward.
var nodes = "ABCD".ToCharArray()
.Select(x => x.ToString())
.ToDictionary(x=>x,x=>new ObservableNamedNode() { Name = x });
var root = nodes.Values.AssembleAsNAryTree(1);
var wRoot = new ReadOnlyLinkedNamedNode(root);
Console.WriteLine(wRoot.ToTreeDiagram(x => x.Name));
/*
Create new {A}
Create new {B}
Create new {C}
Create new {D}
{A}
└ {B}
└ {C}
└ {D}
*/
foreach (var wrp in wRoot.LevelOrder()) {
if (wrp.Children is INotifyCollectionChanged clds) {
clds.CollectionChanged += (s, e) => {
if (e.OldItems != null && e.OldItems[0] is ReadOnlyLinkedNamedNode node) {
Console.WriteLine($"sender:{node.Name}, action:{e.Action}, IsDisposed:{node.IsDisposed}");
}
};
}
}
wRoot.DescendArrivals(x => x.Name, new string[] {"{A}","{B}"}).First().Dispose();
/*
Start disposing {B}.
Start disposing {D}.
Finished disposing {D}.
Start disposing {C}.
sender:{D}, action:Remove, IsDisposed:True
Finished disposing {C}.
sender:{C}, action:Remove, IsDisposed:True
Finished disposing {B}.
*/
Console.WriteLine(wRoot.ToTreeDiagram(x=> $"{x.Name}, IsDisposed = {x.IsDisposed}"));
/*
{A}, IsDisposed = False
└ {B}, IsDisposed = True
*/Wrappers D and C have already been disposed when removed, so HandleRemovedChild is not called for them.
- Wrapper B: disposal started
- Wrapper D: disposal started
- Wrapper D: disposal completed
- Wrapper C: disposal started
- Wrapper C: removed from the child node collection (Remove wrapper D)
- Wrapper C: disposal completed
- Wrapper B: removed from the child node collection (Remove wrapper C)
- Wrapper B: disposal completed
| Process | Scope | Order |
|---|---|---|
| Disposal starts | Target and descendants (reverse level order) | B, D, C |
| Detachment | Descendants (reverse level order) | D, C |
| Disposal completes | Descendants (reverse level order), then target | D, C, B |
The wrapper on which Dispose is called directly is not detached.
It is assumed that Dispose is called directly on the root wrapper.
Thus, disposing the wrapper relinquishes its role as a wrapper and disassembles its descendant wrappers.
If an ancestor exists, as in the example above, the parent wrapper {A} continues to serve as a wrapper and retains a reference to wrapper {B}, which corresponds to the source child node.
If the Children property has not been initialized when Dispose is called, the child wrapper collection is not initialized.
var nodes = "ABCD".ToCharArray()
.Select(x => x.ToString())
.ToDictionary(x=>x,x=>new ObservableNamedNode() { Name = x });
var root = nodes.Values.AssembleAsNAryTree(1);
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
└ B
└ C
└ D
*/
var wRoot = new ReadOnlyLinkedNamedNode(root);
//Create new {A}
wRoot.Children.First().Dispose();
/*
Create new {B}
Start disposing {B}.
Finished disposing {B}.
*/
Console.WriteLine(wRoot.ToTreeDiagram(x=> $"{x.Name}, IsDisposed = {x.IsDisposed}"));
/*
{A}, IsDisposed = False
└ {B}, IsDisposed = True
*/Node B was disposed without accessing its Children property, so nodes C and D were never initialized.