CollectionViewSource MVVM Implementation for WPF DataGrid CollectionViewSource MVVM Implementation for WPF DataGrid wpf wpf

CollectionViewSource MVVM Implementation for WPF DataGrid


You should not create new instances of the observable collection and the collection view. Assign a predicate to the filter property on the collecion view and call Refresh whenever you want to filter the collection.

public class ViewModel : NotifyProperyChangedBase{           string uri;    public ObservableCollection<Movie> MovieList { get; private set; }    public CollectionView MovieView { get; private set; }    public ViewModel(MoveList movieList)    {        MovieList = movieList;        MovieView = GetMovieCollectionView(MovieList);        MovieView.Filter = OnFilterMovie;    }    public void UpdateDataGrid(string uri)    {             this.uri = uri;        MovieView.Refresh();    }    bool OnFilterMovie(object item)    {        var movie = (Movie)item;        return uri.Contains(movie.ID.ToString());    }    public CollectionView GetMovieCollectionView(ObservableCollection<Movie> movList)    {        return (CollectionView)CollectionViewSource.GetDefaultView(movList);    }}


Here is an example of instantiating a CollectionViewSource in order to enable multi-filtering in a DataGrid: http://www.codeproject.com/Articles/442498/Multi-filtered-WPF-DataGrid-with-MVVM

The CollectionViewSource was instantiated in the XAML view but is bound to a collection of objects instantiated in the view model. The view model then uses the CollectionViewSource to filter the data in the DataGrid.

As to what is the right approach to instantiate a CollectionViewSource - that is debatable.


You can skip adding resources by doing this directly : DataContext = new TagViewModel(); and doing your bindings normally. but I highly recommend using Dependency Injection.