WPF Using multiple filters on the same ListCollectionView

后端 未结 2 1555
忘掉有多难
忘掉有多难 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条回答
  •  情歌与酒
    2021-02-05 20:38

    Every time you set Filter property you reset previous filter. This is a fact. Now how can you have multiple filters?

    As you know, there are two ways to do filtering: CollectionView and CollectionViewSource. In the first case with CollectionView we filter with delegate, and to do multiple filters I'd create a class to aggregate custom filters and then call them one by one for each filter item. Like in the following code:

      public class GroupFilter
      {
        private List> _filters;
    
        public Predicate Filter {get; private set;}
    
        public GroupFilter()
        {
          _filters = new List>();
          Filter = InternalFilter;
        }
    
        private bool InternalFilter(object o)
        {
          foreach(var filter in _filters)
          {
            if (!filter(o))
            {
              return false;
            }
          }
    
          return true;
        }
    
        public void AddFilter(Predicate filter)
        {
          _filters.Add(filter);
        }
    
        public void RemoveFilter(Predicate filter)
        {
          if (_filters.Contains(filter))
          {
            _filters.Remove(filter);
          }
        }    
      }
    
      // Somewhere later:
      GroupFilter gf = new GroupFilter();
      gf.AddFilter(filter1);
      listCollectionView.Filter = gf.Filter;
    
    

    To refresh filtered view you can make a call to ListCollectionView.Refresh() method.

    And in the second case with CollectionViewSource you use Filter event to filter collection. You can create multiple event handlers to filter by different criteria. To read more about this approach check this wonderful article by Bea Stollnitz: How do I apply more than one filter? (archive)

    Hope this helps.

    Cheers, Anvaka.

    提交回复
    热议问题