Coding Geek

A blog by Nadeem Iqbal

Silverlight - Convert List to ObservableCollection

 In Silverlight, you will bind the controls such as List/Grid with Observable collection so that any change in the collection automatically reflected on the control.

Often you will be required to convert the List to an observable collection but there isn't exist any method which automatically do so in Silverlight. Moreover, WCF service can only return IEnumerable collection which you may want to convert to the ObservableCollection. So, here is generic way to convert any List to Observable collection;

                        //create an emtpy observable collection object


            var observableCollection = new ObservableCollection<T>();

 

            //loop through all the records and add to observable collection object

            foreach (var item in enumerableList)

                observableCollection.Add(item);

 

            //return the populated observable collection if being used in function

            return observableCollection;

 I hope this will help you ... Cheers:)

 

Comments

webbes said:

Have a look at the contructor :-)

msdn.microsoft.com/.../ms653202.aspx

Cheers,

Wes

# July 23, 2010 3:24 AM

niqbal said:

Have you seen that it works in Silverlight???

# July 23, 2010 3:44 AM

webbes said:

Yep. No problem. Why? What error do you get?

# July 23, 2010 7:36 AM

niqbal said:

Yep, It works now.. In early versions of Silverlight this feature wasn't there.. Thanks webbes

# July 26, 2010 3:18 AM

Wot said:

 foreach (var item in enumerableList)

               observableCollection.Add(item);

sometimes it not works in silverlight (like drag listbox)

# December 29, 2011 9:12 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)