I have a listbox in WPF where users firstname and lastname are listed. I have a textbox, and I am trying to filter as I type by the names. Here is what I am trying: (Nothing is being filtered when I am typing in the textbox)
Here is my VM
#region Members
private CollectionViewSource usercvs = new CollectionViewSource();
private string searchString;
#endregion
#region Properties
public string SearchFilter
{
get
{
return this.searchString;
}
set
{
if (!string.IsNullOrEmpty(this.searchString))
AddFilter();
usercvs.View.Refresh();
this.searchString = value;
}
}
#endregion
#region Methods
private void AddFilter()
{
usercvs.Filter -= new FilterEventHandler(Filter);
usercvs.Filter += new FilterEventHandler(Filter);
}
private void Filter(object sender, FilterEventArgs e)
{
// see Notes on Filter Methods:
var src = e.Item as User;
if (src == null)
e.Accepted = false;
else if (src.LastName != null && !src.LastName.Contains(SearchFilter))
e.Accepted = false;
}
#endregion
}
}
Add an additional property to your ViewModel that exposes the CollectionViewSource and bind your ListBox to that property.
public CollectionViewSource FilteredUsers{
get {
return usercvs.View;
}
}
The ObservableCollection
is not changed when you apply any filters to the CollectionViewSource
, so that you will always see all items. The Filter gets applied to the CollectionViewSource and the filtered result can be accessed by the property View of the class.