With all the possibilities of collections to choose from when writing a WPF application, I'm unsure as to which collections to use when storing my data. It seems like everything could work if I used ObservableCollections and implemented INotifyPropertyChanged.
What are some questions I should be asking myself when using collections in my View Models? In particular, when should I use these collections? :
ObservableCollection
List<ClassA>
IList
CollectionView
ICollectionView
IEnumerable
and any others you might want to list.
and pass it an IEnumerable, but how do I know which is the correct collection? Is it all based on which controls I'm using?
Use ObservableCollection when you want your GUI to update when items are added or removed. An ObservableCollection is a list that has ICollectionChanged implemented automatically.
Use List otherwise.
Use CollectionView when you want to apply sorting, grouping, filtering, aka more complex operations.
If you want the control that takes the collection as a Source to update itself when items to the collection are added/moved/removed/replaced then you must use an ObservableCollection and bind the control's ItemsSource (for example) to that collection.
If you were to use a List<T>, the bound control would not receive any notification to get updated.
This is different than updating the content of each item. No matter (I believe) which collection type you're using the content of each item would be updated only if the item object implements INotifyPropertyChanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With