Search code examples
c#wpfdata-bindingmvvmcollectionviewsource

Using MVVM with CollectionViewSource


I'm trying to use CollectionViewSource to display some data, and all the examples/tutorials I've seen have a custom class built, which they use in another class, which inherits from ObservableCollection. I'm new to both using CollectionViewSource and this is only my third implementation of MVVM, so I might misunderstand the programming pattern, but my question is: where do I put the ObservableCollection class and/or custom class?

I feel like they should go in the Model, but then I'm not sure what gets bound to the View. Do I just build these as external classes, and then reference them in Model/ViewModel?

Any help is appreciated


Solution

  • Firstly, I would say that there is no need to inherit from ObservableCollection<T> unless you are adding functionality to it which I have rarely, if ever, actually needed to do.

    In most cases I create ViewModel properties of type ObservableCollection<T> and then populate them from the Model whenever I load the data. This has the advantage that the Model does not need to use ObservableCollection<T> (it can be any IEnumerable<T>) and it means that later when I (almost inevitably) want to wrap whatever I'm getting back from the Model in another instance-specific view model I am only obliged to change my existing view model classes.

    Once you have a property on your view model you can simply bind your CollectionViewSource to that property and it will do everything from there. It's worth noting that the CollectionViewSource doesn't actually care about the type of the property, so you can expose your collection to the View as an ICollection<T>, IEnumerable<T> or (I believe) even as an object and the CollectionViewSource will still treat it the same as if it is exposed as an ObservableCollection<T>.

    Sorry for the slightly rambling answer. The concise version would be "it depends on the situation" but I tend to follow this general approach in most cases.