In this article I will demonstrate a WPF way of how to create a tree view to which filtering can be applied as a way of searching for a particular node or item in the tree. Using filtering to prune or limit a tree view is something I find very useful and it really bugs me when I can't for example use it to quickly find the option I want to change in the Visual Studio Options. I usually know roughly what I am looking for and it's often faster to type a portion of that than to visually inspect the entire tree, the Window 7 start-menu or the Windows 8 UI are fine examples of this approach being put to good use.
This is obviously not a new problem nor is the internet lacking in example implementations, this article is based on something I did for a friend and I got several requests for the source code after posting it on YouTube so here it is.
Because the subject matter is fairly limited, this will be a relatively short article.
Using the code
Two archives are provided, one for C# and one for VB.NET, so that each can read the sources in the language of their choice.
For the article, since there is so little code involved I've decided to have both the C# andVB.NET code present.
When my friend requested this to be implemented he gave me a short list of requirements that it needed to fulfill:
- 1. It needs to be based on a
- 2. Tree view should, when not filtered, behave like a normal tree view.
- 3. A text input field should accept input that prunes the tree view in real time (by real-time he meant there should be no need to hit Enter or something like that for the filtering to occur).
- 4. The filter conditions should be remembered so that they could easily be re-used (personally, I think this is a bit superfluous as this type of control become really useful when the criterion one enters for the filtering are simple enough to be easily remembered).
- 5. The text input field should not occupy too much screen real estate, whilst at the same time being obvious enough for a first time user to find and understand.
Further, the components of the implementation should lend themselves to MVVM approach as it's likely that the visual appearance would be changed by the UI designers.
I don't know about you, but WPF treeviews have been one of my WPF learning speed bumps. I'm starting to grok it now, but it's taken me a bit. And now I need a treeview that is not only searchable, but filterable too... Something just like this project! :)
And kudo's to the author for providing both C# and VB.