CollectionViewSource Filtering

Here is the follow on to my last post about CollectionView filtering in WPF. This posts shows how to filter a CollectionViewSource object as apposed to a ListCollectionView which the last post covered. CollectionViewSource is mainly used when you want to set up grouping or sorting in XAML (Here is an example). The way you filter a CollectionViewSource in code is different than how you filter a ListCollectionView.  

        CollectionViewSource _view;

        public Window1()
        {
            InitializeComponent();

            string[] myValues = new string[] { "Red Car", "Red Truck", "Blue Car", "Yellow Truck" };

            _view = new CollectionViewSource();
            
            _view.Source = myValues;

            this.DataContext = _view;
        }


        private void FilterTrucks(Object sender, RoutedEventArgs args)
        {
            if (ShowTrucks.IsChecked == true)
                _view.Filter += new FilterEventHandler(IsValueTruck);
            else
            {
                // Remove the filter
                _view.Filter -= new FilterEventHandler(IsValueTruck);
            }
        }


        public void IsValueTruck (object sender, FilterEventArgs e)
        {
            if (e.Item.ToString().Contains("Truck"))
            {
                e.Accepted = true;
            }
            else
            {
                e.Accepted = false;
            }
        }

If you want see what the app looks like when the filter is used see my last post. The app works the same way.

 

This entry was posted in WPF. Bookmark the permalink.

Leave a comment