I wrote a simple code to allow filtering on my datagrid, but I made a mistake in my code. But it still work as expected.
Here is what I did:
- Gettings the source items (from the database)
- Creating the
ICollectionView
from it - Setting my custom filter
- Binding the source to the DataGrid instead of the view
The 4th point is where I made my mistake. I should have bound the view to the DataGrid, not the source, right?
Here is the code:
var mySources = GettingMySource();
var myView = CollectionViewSource.GetDefaultView(mySources);
myView.Filter = MyFilter;
DataGrid.ItemsSource = mySources;
Somewhere else in my code (when the user enter a filter), I just call:
myView.Refresh();
And it works... The elements that don't match with my filter are removed from the CollectionView and from the UI, but my source list is unchanged...
Can someone explain me how this can work ?
MSDN says:
So it seems that while you tell the DataGrid to use the source, it still automatically takes the (default) view which is shared over all bindings and has your filter applied to it.
edit:
it also says that
So, it would not have filtered if you had applied the filter to the
View
of anew CollectionViewSource(mySources)
instead of the default view.