How to filter a wpf treeview hierarchy using an ICollectionView?

前端 未结 6 1928
盖世英雄少女心
盖世英雄少女心 2020-12-29 22:26

I have a hypothetical tree view that contains this data:

RootNode
   Leaf
   vein
SecondRoot
   seeds
   flowers

I am trying to filter the

6条回答
  •  难免孤独
    2020-12-29 22:32

    This is how I filtered the items on my TreeView:

    I have the class:

    class Node
    {
        public string Name { get; set; }
        public List Children { get; set; }
    
        // this is the magic method!
        public Node Search(Func predicate)
        {
             // if node is a leaf
             if(this.Children == null || this.Children.Count == 0)
             {
                 if (predicate(this))
                    return this;
                 else
                    return null;
             }
             else // Otherwise if node is not a leaf
             {
                 var results = Children
                                   .Select(i => i.Search(predicate))
                                   .Where(i => i != null).ToList();
    
                 if (results.Any()){
                    var result = (Node)MemberwiseClone();
                    result.Items = results;
                    return result;
                 }
                 return null;
             }             
        }
    }
    

    Then I could filter results as:

    // initialize Node root
    // pretend root has some children and those children have more children
    // then filter the results as:
    var newRootNode = root.Search(x=>x.Name == "Foo");
    

提交回复
热议问题