Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter ItemsSource

With this code I'm setting the ItemsSource of my datagrid. However I've got more wpf controls that are needed to filter the datagrid, for example from a time range. I could write a new query for this but that seems unnecessary as the data is already available, I just need to filter it. What's the best way to do this?

Any help I could get would be really appreciated!

DateTime dateStart = CalenderSearch.SelectedDates.First();
DateTime dateEnd = CalenderSearch.SelectedDates.Last();

ObjectQuery<Fouten> fouten = eventsEntities.Foutens;

var query =
    (from fout in fouten
    where dateStart <= fout.Datum && dateEnd >= fout.Datum && fout.Rapporten.Treinen.NameTrein == trein.NameTrein
    orderby fout.Datum, fout.Time
    select new
    {
        Datum = fout.Datum,
        Time = fout.Time,
        FoutCode = fout.FoutCode,
        Omschrijving = fout.Omschrijving,
        Teller = fout.Teller,
        Module = fout.Module,
        FoutId = fout.FoutId

    }).AsEnumerable().Select(x => new Fouten
    {
        Datum = x.Datum,
        Time = x.Time,
        FoutCode = x.FoutCode,
        Omschrijving = x.Omschrijving,
        Teller = x.Teller,
        Module = x.Module,
        FoutId = x.FoutId
    }).ToList();

if (query.Count == 0)
    foutensDataGrid.ItemsSource = null;
else
    foutensDataGrid.ItemsSource = query;

1 Answers

In WPF, each collection that are used as an ItemsSource in a GUI element have an ICollectionView associated with it.
ICollectionView has a Filter property, which is of type Predicate<object>.

If you set this Filter and call Refresh() afterwards, the DataGrid will update itself to only show the items where Filter returned true.

An example how you could use this:

var collectionView = CollectionViewSource.GetDefaultView(foutensDataGrid.ItemsSource);
collectionView.Filter = o => {
    var fouten = o as Fouten;
    //do your filtering, e.g.
    return fouten.Datum <= dateEnd && fouten.Datum >= dateStart;
}
collectionView.Refresh();
like image 156
Domysee Avatar answered Jul 25 '26 11:07

Domysee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!