Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which collection to use in WPF [closed]

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?

like image 667
Kcvin Avatar asked Jan 28 '26 12:01

Kcvin


2 Answers

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.

like image 137
Julien Avatar answered Jan 31 '26 00:01

Julien


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.

like image 36
New Dev Avatar answered Jan 31 '26 01:01

New Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!