A very popular means of searching through a list of items (such as e-mails) is to type some text into a TextBox and only show the items which contain that text. This blog post demonstrates one way to do that in WPF.
What the user is actually doing in this situation, whether or not (s)he realizes it, is applying a filter to the list of items. If the user types “ar” into the Search TextBox, we must filter out all of the items which do not contain the text “ar”. In other words, we must only filter in the items which contain that text.
WPF has built-in support for filtering items in a list. ICollectionView has a Filter property, which can be set to an instance of Predicate<Object> — a delegate which takes a single Object argument and returns a bool. Each item in the list is passed through that filter to determine if it is filtered in or out.
Without further ado, let’s first take a look at what the demo application associated with this post looks like:
After the user types “ar” into the Search TextBox, the UI looks like this:
As you can see above, typing into the Search TextBox removes all items which do not contain the search text. Now let’s see how to implement this functionality.
First we will set up the list of items which the ListBox displays:
That’s just a plain old array of strings. There’s nothing special here yet. Next we’ll see the XAML which declares our simple UI:
That basically just creates a TextBox and a ListBox. The TextBox is not bound to anything, and the ListBox is bound to the array of strings seen previously. There’s still not much of interest here yet. However, now the plot thickens as we start exploring the code-behind.
Here is the Window’s constructor, which connects the Search TextBox with a class I wrote called TextSearchFilter:
That constructor grabs the array of strings declared in XAML and then asks for the default view which WPF wraps around it, for data binding purposes. Once we have that view at our disposal, we simply pass it along to a new instance of TextSearchFilter so that it can perform its magic.
Here is the entire TextSearchFilter class:
That’s the code which does real work. TextSearchFilter applies a filter to the view (which wraps our array of strings, seen previously) and then hooks the Search TextBox’s TextChanged event. When the TextChange event fires, it updates the text used to filter in/out items in the ListBox, and then tells the view to re-apply its filter. Via the splendor known as “anonymous methods” we can write this entire class in its constructor, which makes it nice and compact.
Here is the source code for the demo project: Searching for items in a ListBox (demo project)
Be sure to change the file extension from .DOC to .ZIP and then decompress it.