在我的程序中,我有一个TreeView
,它是通过MVVM结构实现的。我在此树的数据模型中实现了Parent
属性,但无法弄清楚如何设置子项的父级。
TreeViewViewModel:
private TreeModel createNewNode()
{
return new TreeModel()
{
Parent = null,
Children =
{
new BlockingTreeModel() { Parent = ?? }
};
}
的TreeModel:
private ObservableCollection<BlockingTreeModel> _parent;
public ObservableCollection<BlockingTreeModel> Parent
{
get { return _parent; }
set
{
_parent = value;
NotifyPropertyChange(() => Parent);
}
}
如何在TreeViewViewModel中设置子节点的Parent
属性?
谢谢。
答案 0 :(得分:1)
您无法使用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
的{{1}}方法,并对每个添加的项目执行一些操作,如下所示:
Add()
然后您的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
然后允许您保留Object / Collection Initializer语法,因为您不再需要显式设置Children的Parent(HierarchicalCollection正在为您执行此操作):
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);
}
}