i want to filter wpf datagrid, and i do that in this way,i use datagridcolumnsheader and put a textbox in headers and use them filter each column:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textSearch = (sender as TextBox).Text;
CollectionViewSource.Filter += new FilterEventHandler(FilterEvent);
}
and
private void FilterEvent(object sender, FilterEventArgs e)
{
if (propertyName == null)
return;
var a = e.Item.GetType().GetProperty("Name");
if (a != null)
{
if (textSearch != "")
{
var s = a.GetValue(e.Item, null);
if (s != null)
e.Accepted = s.ToString().Contains(textSearch);
else
e.Accepted = false;
}
else
e.Accepted = true;
}
}
it works fine for a column like id,but when i want to make filter on another column like name ,it filters the list just by name and dosen't keep the past filter,for example if i filter the list by id=2 ,and then filter it by name='a' ,it just filters list by name='a'!
To apply multiple filters to a collection bound to a WPF DataGrid you should instantiate a CollectionViewSource object as a proxy between the view and the collection (this will also work with other collection controls). Doing so will allow you to subscribe multiple filter event handlers to it's Filter event. Filters are applied in the order in which they are subscribed and can be removed by unsubscribing them.
If you used the CollectionViewSource.GetDefaultView() static method in your codebehind or ViewModel, this will return an instance of an ICollectionView which will only support a single filter with a Filter property.
Your can find an example with source code here http://www.codeproject.com/Articles/442498/Multi-filtered-WPF-DataGrid-with-MVVM