Tuesday, June 19, 2007 10:51 AM
rudi
How to filter a list
I have a list of blogs and I want to be able to filter these items by just typing leters contained in the title of these blogs and the list box must then only show the items which contains these leters...
I started by creating a List<string> of blogs
List<string> blogs;
The next step is to initialize this list and add some content...
blogs = new List<string>();
blogs.Add("Zlatan's Blog ");
My WPF window contains a TextBox names txtSearch and a ListBox named lbItems. Next, you have to bind the blogs list to the ListBox
lbItems.ItemsSource = blogs;
Now is a good time to save and test. A list of all the blogs previously added should now be displayed. Next step is to add a ICollectionView
ICollectionView
view;
Next we have to find the defualt view for this array
view =
CollectionViewSource.GetDefaultView(blogs);
We also need to add two delegates, the first delegate is for Filter
view.Filter = delegate(object obj)
{
if ( string.IsNullOrEmpty(txtSearch.Text))
return true;
string str = obj.ToString();
if (string.IsNullOrEmpty(str))
return false;
int index = str.IndexOf( txtSearch.Text, 0, StringComparison.InvariantCultureIgnoreCase);
return index > -1;
};
This delegate checks the provided item if it contains any part of the provided search string (txtSearch). Lastly, we need to add another delegate for the TextChanged event of the txtSearch to refresh the view
txtSearch.TextChanged += delegate
{
view.Refresh();
};
And that is all that is needed to automatically filter the items based on the provided part of text.
Filed under: WPF