wpfentity-frameworkfilterobservablecollection

How can I provide dynamic filtering on an entity collection?


I have a class ShipmentsCollection that inherits ObservableCollection which contains shipment objects (entities). This is displayed in a listbox on my ShipmentsView UserControl. My intent is to allow a user to type into a textbox above the list and filter the list with items that contain that string, as well as filter based on several checkbox and radiobutton based options (Delivery status and orderby direction).

I have tried this several ways, but none seem very elegant or really functional. Things I have tried follows:

I am seeking some good ideas in regard to implementing this functionality in an MVVM design pattern. I expect to have at most 200 objects in the list, so it will not be an enormous filter operation.


Solution

  • Your first option would be the one I would suggest. To get the auto-filter to work based on typing, I'd do something like a SearchString property in my ViewModel, bind the textbox text to that, and set the UpdateSourceTrigger in the binding to PropertyChanged so it will call the SearchString PropertyChanged event every time a key is typed instead of waiting until the box loses focus.

    XAML:

    <TextBox Text="{Binding SearchString, UpdateSourceTrigger=PropertyChanged}" />
    

    ViewModel: With the above property set to PropertyChanged, the "Set" method gets called anytime a key is typed instead of just when the textbox loses focus.

    private string _searchString;
    public string SearchString
    {
        get { return _searchString; }
        set
        {
            if (_searchString != value)
            {
                _searchString = value;
                OnPropertyChanged("SearchString");
            }
        }
    }