【问题标题】:Get the Parent List in a TreeView在 TreeView 中获取父列表
【发布时间】:2013-05-21 12:42:14
【问题描述】:

我的问题如下: 我有一个treeView,它绑定到ItemsSource。 SelectedItem 已绑定 到我的 ViewModel 中名为 SelectedItem 的属性。

ItemsSource 的构建方式如下:

public class Item
{
      public Header { get; set; }
      public ObservableCollection<Item> ItemChildren { get; set; }
.
.
.
}

我想删除、重新排序……项目。所以我需要 SelectedItem 的父列表来执行此操作。我可以研究该项目的所有列表,但该项目可以存在两次,并且对于分隔符,该项目可以为空。

有谁知道如何获取所选项目的父列表?

非常感谢!

问候, 凯文

【问题讨论】:

    标签: c# wpf binding treeview datacontext


    【解决方案1】:

    如果那是树,那么您不需要父母列表,而只需要对父母的引用:

    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;
    
    }
    

    此解决方案比您开始使用的解决方案更复杂。父对象必须跟踪其子对象,并确保每次添加子对象时都将子对象的 Parent 设置为它。

    我一直在输入这段代码而没有进行语法检查,但它恰到好处。您可以在本文中找到几乎相同问题的完整源代码:How to Implement Collection Property to Contain Unique Objects

    编辑:请注意,上面代码中的Item 类不允许调用者设置ItemChildren 集合。该集合由 Item 实例创建和服务,并且不允许任何人更改它。但是任何人都可以在其中添加/删除项目。另一件事是 Item 处理新添加的子项的方式 - 如果有人尝试添加具有非空父引用的项,您可以随意抛出 InvalidOperationException!这将确保您的结构仍然是树。例如,如果参数已经是当前节点的祖先,XmlNode 类 (System.Xml) 从 AppendChild 方法中抛出 InvalidOperationException。当Item 有机会验证添加到其中的元素时,可能性是无穷无尽的。

    【讨论】:

    • 非常感谢。这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2014-10-21
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多