Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of ObservableCollection in .net?

What is the use of ObservableCollection in .net?

like image 202
santosh singh Avatar asked Nov 25 '10 16:11

santosh singh


People also ask

What is an ObservableCollection?

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.

What is ObservableCollection in xamarin forms?

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.

What is the difference between ObservableCollection and list?

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.

What is the difference between ObservableCollection and BindingList?

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.


1 Answers

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         }     } } 
like image 140
Craig Suchanec Avatar answered Sep 24 '22 00:09

Craig Suchanec