What is the use of ObservableCollection in .net?
An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.
If you want the ListView to automatically update as items are added, removed and changed in the underlying list, you'll need to use an ObservableCollection . ObservableCollection is defined in System.Collections.ObjectModel and is just like List , except that it can notify ListView of any changes: C# Copy.
The true difference is rather straightforward:ObservableCollection implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList implements IBindingList.
The practical difference is that BindingList is for WinForms, and ObservableCollection is for WPF. From a WPF perspective, BindingList isnt properly supported, and you would never really use it in a WPF project unless you really had to.
ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.
The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections
class Handler { private ObservableCollection<string> collection; public Handler() { collection = new ObservableCollection<string>(); collection.CollectionChanged += HandleChange; } private void HandleChange(object sender, NotifyCollectionChangedEventArgs e) { foreach (var x in e.NewItems) { // do something } foreach (var y in e.OldItems) { //do something } if (e.Action == NotifyCollectionChangedAction.Move) { //do something } } }
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