My blog has moved!

Visit http://blog.adamroderick.com/ and update your bookmarks.

Friday, July 9, 2010

Extension Method to Populate an ObservableCollection

I have been building a business application using the model-view-viewmodel pattern and RIA Services in Silverlight 4.  Typically, a viewmodel class will make a call to one of the services to get some information.  If this information is a collection to be displayed, I will populate an ObservableCollection property with the collection of items. 

When Silverlight first loads the control, the UI bindings subscribe to the property changed events that the ObservableCollection property fires anytime items are added or removed from the collection.  If I populate my ObservableCollection property like the following, it is a new object on the heap, and the UI binding is not subscribed to anything on the new object:

this.ObservableCollectionProperty = new ObservableCollection(collectionReturnedFromService);

To make things work the way I wanted, I had to call Clear on the existing ObservableCollection and then add each item.  This was common enough that it merited an extension method:

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home