Read this article in your language IT | EN | DE | ES
Found a good article and helped with a problem I was having, trying to send a list of collection back to a WCF service that was set to accept Observable Collections.
Source: http://smehrozalam.wordpress.com/2009/01/18/ienumerabletoobservablecollection/
| In WPF/Silverlight, binding UI objects such as DataGrid or ListBox to collections is typically done using an ObservableCollectioninstead of the generic List object. This way, our UI is automatically synchronized since the observable collection provides event notification to WPF data binding engine whenever items are added, removed, or when the whole list is refreshed. The LINQ extension methods that return a collection actually return IEnumerable<T>. The .NET framework for Silverlight provides built-in extension methods to convert IEnumerable<T> to List<T> and Array<T> but there’s no method available to convert the collection to ObservableCollection<T>(WPF developers can simply use this constructor overload) . So here’s one you may find useful: - Public Static Class CollectionExtensions
- {
- public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerableList)
- {
- if (enumerableList != null)
- {
- //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
- return observableCollection;
- }
- return null;
- }
- }
Extension methods are very powerful and I am planning to post an example demonstrating their potential. |
I’ve converted the above example to VB.Net version for you to copy.
Public Shared Function ToObservableCollection(Of T)(ByVal enumerableList As IEnumerable(Of T)) As ObservableCollection(Of T)
If enumerableList IsNot Nothing Then
'create an emtpy observable collection object
Dim observableCollection As New ObservableCollection(Of T)()
'loop through all the records and add to observable collection object
For Each item As T In enumerableList
observableCollection.Add(item)
Next
'return the populated observable collection
Return observableCollection
End If
Return Nothing
End Function
Now you can call your List and send it back as a ObservableCollection
0e7ac644-8708-410d-892f-666c2a3c8fa7|0|.0
.Net Framework, Code Snippets, Programming, VB.NET, WCF, SilverLight
programming, vb.net, code snippets, wcf, silverlight