ListBox ItemsSource dynamic filter WPF


I want to make a UI virtualization via the datasource.

The idea is to "Filter" what i send to the UI (a listbox in my case).

I noticed that the ItemsSource (an observable collection) is read once and that changing the Filter does not trigger refreshing...

I don't understand why Thanks Jonathan

I'll try to be more clear :

I have CollectionViewSource:

<CollectionViewSource x:Key="MyItemView"
                                  Source="{Binding Path=Model.CurrentItem}" />

Then use this datasource in my ListBox:

<ListBox x:Name="myListBox"
                 ItemsSource="{Binding Source={StaticResource MyItemView}}"

I thought to implement a converter that would return a filtered collection (base on the current date):

<ListBox x:Name="myListBox"
                 ItemsSource="{Binding Source={StaticResource MyItemView}, Converter={StaticResource FilterByTime}, ConverterParameter=CurrentDate }"

Which i implemented this way:

public class FilterByTimeConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            if (value != null)
                System.Windows.Data.ListCollectionView list = value as System.Windows.Data.ListCollectionView;

                var model = DI.Resolve<ApplicationModel>();

                list.Filter = delegate(object item) 
                    bool r= (((MyModel)item).OriginalDate > model.TimeLine.CurrentDate.AddMonths(-1) 
                        && (((MyModel)item).OriginalDate < model.TimeLine.CurrentDate.AddMonths(1)));

                   // Console.WriteLine ("{0}<{1}<{2} : {3}",model.MyListBox.CurrentDate.AddMonths(-1),((MyModel)item).OriginalDate ,model. MyListBox.CurrentDate.AddMonths(1),r.ToString());
                    return r;

                return list;

            return DependencyProperty.UnsetValue;

This works fine...but only when bounf the first time. When the Current Date is changed and that the filter is changed, the list is not updated.

Perhaps i should listen to the CurrentDate PropertyChange, but i'm confused how to do this

Thanks Jonathan

1/11/2019 10:14:13 AM

The CollectionViewSource itself supports filtering via its Filter property. Why don't you put your filtering logic in there?

9/27/2011 3:14:42 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow