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
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 useObservableCollection<T>(it can be anyIEnumerable<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
CollectionViewSourceto that property and it will do everything from there. It’s worth noting that theCollectionViewSourcedoesn’t actually care about the type of the property, so you can expose your collection to the View as anICollection<T>,IEnumerable<T>or (I believe) even as anobjectand theCollectionViewSourcewill still treat it the same as if it is exposed as anObservableCollection<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.