Serializing ObservableCollection (of T) in VB.Net

I have been trying to get MVVM running in VB.Net for a while and start with some of my entities using List (of T) s which I xml serialize to disk. I have now updated the classes used by lists to implement INotifyPropertyChanged, so I also changed List (of T) s to ObservableCollection (of T) s.

After that, the XML serializer stops working: "(A colleague told me that ObservableCollections, unlike generic lists, are not serializable.

If so, how can I make them Serializable? Thanks in Advance ~!: D

+2


source to share


2 answers


Your college is half correct. ObservableCollection(Of T)

is indeed serializable, but this happens through a binary serializer, not XML.

What can you do to get around this is to bind the serialization of any collections ObservableCollection(Of T)

with List(Of T)

. Just do the conversion at the serialization point.



For example...

Public Sub Serialize(ByVal col as ObservableCollection(Of Integer))
  Dim list = New List(Of Integer)(col)
  ReallySerialize(list)
End Sub

Public Function Unserialize() As ObserableCollection(Of Integer)
  Dim list = ReallyUnserialize()
  return New ObservableCollection(Of Integer)(list)
End Function

      

+2


source


@JaredPar's answer re only Binary Serializer does not work with Xml, XmlSerializer does work for me (in VS2010).



//ObservableCollection<Customer> customers = Code to load customers 

//write to file
   XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
   using (StreamWriter wr = new StreamWriter("myfile.xml")) {
        xs.Serialize(wr, customers);
   }

      

+2


source







All Articles