Home > Silverlight > Why to use ObservableCollection instead of List in Silverlight

Why to use ObservableCollection instead of List in Silverlight


List<T> represents a strongly typed list of objects that can be accessed by index. It provides methods to search, sort, and manipulate lists.

We use List<T> to assign DataSource to Controls in ASP.Net (eg. DataGrid, Dropdownlist etc). Once we assign List<T> to DataGrid it becomes stateless. DataGrid will be displaying data even if all the items of that collection have been removed. To reflect the changes in DataGrid user has to refresh the page. To solve this problem in Silverlight we have ObeservableCollection<T> collection. ObservableCollection is a generic dynamic data collection. It is capable to provide item added/deleted notifications to client with the help of “INotifyCollectionChanged” interface. INotifyCollectionChanged interface has an event “PropertyChanged”. It occurs when a property value is changed.

WCF service proxy class in Silverlight uses ObservableCollection<T> by default.

While adding the service reference to the Application we can change Collection type.

clip_image002

As you can see in below code that type of e.Result is ObservableCollection<T> because I have set collection type to ObservableCollection while adding reference. Type of e.Result gets changed automatically according to Collection Type.

clip_image004

Implemention of INotifyPropertyChanged interface

In below code Employee class implements INotifyPropertyChanged interface and whenever name property is changed we are calling onPropertyChanged method. Further it will raise PropertyChanged event and it will send notification to client.

clip_image005

Happy Coding :)

MSCoder

About these ads
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: