How to filter a wpf treeview hierarchy using an ICollectionView?

前端 未结 6 1889
盖世英雄少女心
盖世英雄少女心 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:28

    Why do you need filters or CollectionSource? Here is a simple MVVM way to handle TreeView items.

    You can make items visible, collapsed, change color, highlight, flash, whatever, simply by using DataTriggers:

    public class Item : INotifyPropertyChanged
    {
        public string Title                     { get; set; } // TODO: Notify on change
        public bool VisibleSelf                 { get; set; } // TODO: Notify on change
        public bool VisibleChildOrSelf          { get; set; } // TODO: Notify on change
        public ObservableCollection<Item> Items { get; set; } // TODO: Notify on change
    
        public void CheckVisibility(string searchText)
        {
             VisibleSelf = // Title contains SearchText. You may use RegEx with wildcards
             VisibleChildOrSelf = VisibleSelf;
    
             foreach (var child in Items)
             {
                 child.CheckVisibility(searchText);
                 VisibleChildOrSelf |= child.VisibleChildOrSelf;
             }
        }
    }
    
    public class ViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Item> Source { get; set; } // TODO: Notify on change
        public string SearchText                 { get; set; } // TODO: Notify on change
    
        private void OnSearchTextChanged()  // TODO: Action should be delayed by 500 millisec
        {
            foreach (var item in Source) item.CheckVisibility(SearchText);
        }
    }
    
    <StackPanel>
        <TextBox Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                     MinWidth="200" Margin="5"/>
    
        <TreeView ItemsSource="{Binding Source}" Margin="5">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Items}">
                    <TextBlock Text="{Binding Title}" />
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
            <TreeView.ItemContainerStyle>
                <Style TargetType="Control">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding VisibleChildOrSelf}" Value="false">
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding VisibleSelf}" Value="false">
                            <Setter Property="Foreground" Value="Gray"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TreeView.ItemContainerStyle>
        </TreeView>
    <StackPanel>
    

    I'm going to include the complete example into my WPF library:

    https://www.codeproject.com/Articles/264955/WPF-MichaelAgroskin

    0 讨论(0)
  • 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<Node> Children { get; set; }
    
        // this is the magic method!
        public Node Search(Func<Node, bool> 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");
    
    0 讨论(0)
  • 2020-12-29 22:34

    The only way I've found to do this (which is a bit of a hack), is to create a ValueConverter that converts from IList to IEnumerable. in ConvertTo(), return a new CollectionViewSource from the passed in IList.

    If there's a better way to do it, I'd love to hear it. This seems to work, though.

    0 讨论(0)
  • 2020-12-29 22:37

    I decided to use the treeview by Philipp Sumi mentioned here : http://www.codeproject.com/KB/WPF/versatile_treeview.aspx

    And applied a filter to it as shown here : http://www.hardcodet.net/2008/02/programmatically-filtering-the-wpf-treeview

    I couldn't recommend it enough :)

    0 讨论(0)
  • 2020-12-29 22:42

    Unfortunately there is no way to make same Filter apply to all nodes automatically. Filter is a property (not a DP) of ItemsCollection which is not DependencyObject and so DP Value inheritance isn't there.

    Each node in the tree has its own ItemsCollection which has its own Filter. The only way to make it work is to manually set them all to call the same delegate.

    Simplest way would be to expose Filter property of type Predicate<object> at your ToolBoxViewModel and in its setter fire an event. Then ToolboxItemViewModel will be responsible for consuming this event and updating its Filter.

    Aint pretty and I'm not sure what the performance would be like for large amounts of items in the tree.

    0 讨论(0)
  • 2020-12-29 22:48

    You can get the TreeViewItem for a given element in a tree using ItemContainerGenerator and once you have that you are in a position to set the Filter.

    0 讨论(0)
提交回复
热议问题