C# 在树视图中获取父列表
我的问题如下: 我有一个树状视图,它绑定到ItemsSource。SelectedItem已绑定 指向我的ViewModel中名为SelectedItem的属性 ItemsSource的构建类似于:C# 在树视图中获取父列表,c#,wpf,binding,treeview,datacontext,C#,Wpf,Binding,Treeview,Datacontext,我的问题如下: 我有一个树状视图,它绑定到ItemsSource。SelectedItem已绑定 指向我的ViewModel中名为SelectedItem的属性 ItemsSource的构建类似于: public class Item { public Header { get; set; } public ObservableCollection<Item> ItemChildren { get; set; } . . . } 公共类项目 { 公共头{ge
public class Item
{
public Header { get; set; }
public ObservableCollection<Item> ItemChildren { get; set; }
.
.
.
}
公共类项目
{
公共头{get;set;}
公共ObservableCollection项子项{get;set;}
.
.
.
}
我想删除,重新排序。。。这些项目。因此,我需要SelectedItem的父列表来执行此操作。我可以研究该项的所有列表,但该项可以存在两次,对于分隔符,该项可以为空
有人知道如何获取所选项目的父列表吗
非常感谢
问候,,
Kevin如果这是一棵树,那么您不需要父母列表,只需要对父母的引用:
public class Item
{
public Item()
{
_col = new ObservableCollection<Item>();
_col.CollectionChanged +=
new NotifyCollectionChanged(ItemChildren_CollectionChanged);
}
public Header { get; set; }
public ObservableCollection<Item> ItemChildren
{ get { return _col; } }
public Item Parent { get { return _parent; } }
private void ItemChildren_CollectionChanged(
object sender,
NotifyCollectionChangedEventArgs e)
{
// for all newly added items: item._parent = this;
// for all removed items: item._parent = null;
}
private Item _parent;
private ObservableCollection<Item> _col;
}
公共类项目
{
公共项目()
{
_col=新的可观察集合();
_col.CollectionChanged+=
新NotifyCollectionChanged(ItemChildren\u CollectionChanged);
}
公共头{get;set;}
公共可观察收集项目子项
{get{return\u col;}}
公共项父项{get{return\u Parent;}
私有无效项子项集合已更改(
对象发送器,
NotifyCollectionChangedEventArgs(e)
{
//对于所有新添加的项目:项目。\父项=此;
//对于所有删除的项:项。\u parent=null;
}
私人物品(家长);;
私人可观测收集;
}
此解决方案比您开始使用的更复杂。父对象必须跟踪其子对象,并确保每次向其添加子对象时都将子对象的父对象设置为它
我一直在没有语法检查的情况下输入这段代码,但它切中要害。您可以在本文中找到几乎相同问题的完整源代码:
编辑:请注意,上面代码中的
Item
类不允许调用者设置ItemChildren
集合。该集合由Item实例创建并提供服务,不允许任何人对其进行更改。但任何人都可以添加/删除其中的项目。还有一件事是Item处理新添加的子项的方式-如果有人试图添加具有非空父引用的项,您可以自由抛出invalidoOperationException
!这将确保您的结构仍然是树。例如,如果参数已经是当前节点的祖先,则XmlNode
类(System.Xml
)从AppendChild
方法中抛出InvalidOperationException
。当项目
有机会验证添加到其中的元素时,可能性是无穷的。非常感谢。那正是我要找的!