您不能为此使用Object Initializer语法。
像这样改变它:
private TreeModel createNewNode()
{
var newNode = new TreeModel();
newNode.Children.Add(new BlockingTreeModel() {Parent = newNode});
return newNode;
}
此外,您的对象模型对我来说似乎是错误的。在树状结构中,项目可能有 N 个孩子,但只有 1(一个)父母。因此,您的Parent
属性应该这样定义:
private TreeModel _parent;
public TreeModel Parent
{
get { return _parent; }
set
{
_parent = value;
NotifyPropertyChange(() => Parent);
}
}
-------------------------------------------------- -----------------------------------------
或者,您可以覆盖ObservableCollection
'sAdd()
方法,并对每个添加的项目执行一些操作,如下所示:
public class HierarchicalObservableCollection<TParent, TItems> : ObservableCollection<TItems>
{
public TParent Parent { get; protected set; }
public Action<TItems, TParent> ItemParentSetter { get; protected set; }
public HierarchicalObservableCollection(TParent parent, Action<TItems, TParent> parentSetter)
{
Parent = parent;
ItemParentSetter = parentSetter;
}
public new void Add(TItems item)
{
if (item != null)
ItemParentSetter(item, Parent);
base.Add(item);
}
}
然后您的TreeModel
课程可以更改为:
public class TreeModel
{
public TreeModel Parent { get; set; }
public HierarchicalObservableCollection<TreeModel, TreeModel> Children { get; set; }
public TreeModel()
{
Children = new HierarchicalObservableCollection<TreeModel, TreeModel>(this, (i, p) => i.Parent = p);
}
}
这将允许您保留 Object / Collection Initializer 语法,因为您不再需要显式设置 Children's Parent(HierarchicalCollection 正在为您执行此操作):
return new TreeModel()
{
Parent = null,
Children =
{
new BlockingTreeModel() // <- this will call Add() which will set the Parent too.
};