WPF Using multiple filters on the same ListCollectionView

后端 未结 2 1582
忘掉有多难
忘掉有多难 2021-02-05 19:42

I\'m using the MVVM design pattern, with a ListView bound to a ListCollectionView on the ViewModel. I also have several comboboxes that are used to filter the ListView. When t

2条回答
  •  萌比男神i
    2021-02-05 20:30

    Every time the user filters, your code is replacing the Filter delegate in your collection view with a new, fresh one. Moreover, the new one only checks the particular criteria the user just selected with a ComboBox.

    What you want is a single filter handler that checks all criteria. Something like:

    public MyViewModel()
    {
        products = new ObservableCollection();
        productsView = new ListCollectionView(products);
        productsView.Filter += FilterProduct;
    }
    
    public Item SelectedItem
    {
        //get,set omitted. set needs to invalidate filter with refresh call
    }
    
    public Type SelectedType
    {
        //get,set omitted. set needs to invalidate filter with refresh call
    }
    
    public Category SelectedCategory
    {
        //get,set omitted. set needs to invalidate filter with refresh call
    }
    
    public ICollection FilteredProducts
    {
        get { return productsView; }
    }
    
    private bool FilterProduct(object o)
    {
        var product = o as Product;
    
        if (product == null)
        {
            return false;
        }
    
        if (SelectedItem != null)
        {
            // filter according to selected item
        }
    
        if (SelectedType != null)
        {
            // filter according to selected type
        }
    
        if (SelectedCategory != null)
        {
            // filter according to selected category
        }
    
        return true;
    }
    

    Your view can now just bind to the appropriate properties and the filtering will just work.

提交回复
热议问题