tags:

views:

960

answers:

2

I have a hypothetical tree view that contains this data:

RootNode
   Leaf
   vein
SecondRoot
   seeds
   flowers

I am trying to filter the nodes in order to show only the nodes that contain a certain text. Say if I specify "L", the tree will be filtered and show only RootNode->Leaf and SecondRoot->flowers (because they both contain the letter L).

Following the m-v-vm pattern, I have a basic TreeViewViewModel class like this:

public class ToolboxViewModel
{
    ...
    readonly ObservableCollection<TreeViewItemViewModel> _treeViewItems = new ObservableCollection<TreeViewItemViewModel>();
    public ObservableCollection<TreeViewItemViewModel> Headers
    {
        get { return _treeViewItems; }
    }

    private string _filterText;
    public string FilterText
    {
        get { return _filterText; }
        set
        {
            if (value == _filterText)
                return;

            _filterText = value;

            ICollectionView view = CollectionViewSource.GetDefaultView(Headers);
            view.Filter = obj => ((TreeViewItemViewModel)obj).ShowNode(_filterText);
        }
    }
    ...
}

And a basic TreeViewItemViewModel:

public class ToolboxItemViewModel
{
    ...
    public string Name { get; private set; }
    public ObservableCollection<TreeViewItemViewModel> Children { get; private set; }
    public bool ShowNode(string filterText)
    {
        ... return true if filterText is contained in Name or has children that contain filterText ... 
    } 
    ...
}

Everything is setup in the xaml so I see the treeview and search box.

When this code is exercised, the filter only applies to the Root nodes which is insufficient. Is there a way to make the filter trickle down in the hierarchy of nodes so that my predicate is called for every node ? In other words, can the filter be applied to the TreeView as a whole ?

A: 

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.

Andy
A: 

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.

Alex_P