WPF - Tree child item needs reference to its parent node in its constructor but it's received only after the constructor - Solution required
I got a tree structure in C#.
Each node in the tree contains a reference to a parent and a collection of children. The process of creating a child node is likewise -
- A parent node creates a child item
- The child runs all of its constructor logic
- After the child has exited its constructor, its instance is added into the parent's children collection, and the child's Parent property is updated accordingly.
This has worked great for me just up until now. I encountered a situation where some objects needed a reference to their parent already in their constructor, even th开发者_Go百科ough they did not have it yet, and will receive it only after they exit the constructor and be added to their parent's collection. (As in stage 3)
I thought of a possible solutions which I'm not sure of -
Each parent node should propagate itself to its child upon creation. The problem with this case is a bit more clumsy constructors but also the Parent property would be set twice. Once in step 2, and one more time in step 3.
I figured that this must be a common problem, therefore someone must have found out a better solution.
Just for general knowledge - this tree structure is ViewModel based for WPF's TreeView.
Comments will be much appreciated.
Thanks!
The first question I'd ask is: why doesn't your parent class implement a method that looks like this?
public void AddChild(object parameters)
{
Children.Add(new ChildNode(this, parameters));
}
Is there any other circumstance in your application in which a ChildNode
object can be created? If so, what is it, and why does it exist?
I think you have one of two options:
- Add the parent as a constructor parameter (not that unusual)
- Make the logic dependent on the parent only run once the parent is set, either by listening for a property changed event or by overriding the OnParentChanged protected virtual method (probably the better solution). This assumes that you announce parent changes using a standard accessor, property change notifier (INotifyPropertyChanged), and protected virtual method access point for raising the event. It is better, as the root event raiser, to handle your custom logic in the protected method.
I'd prefer the second solution, because it will allow you to rerun the logic if your node happens to get re-parented. It also allows for your nodes to be trimmed from the tree (Parent = null).
精彩评论