anon
anon

Reputation:

Trouble with DataContractSerializer

I'm trying to make DataContract Serializer work with one of my class.

Here it is :

public class MyOwnObservableCollection<T> : ObservableCollection<T>, IDisposable
    where T : IObjectWithChangeTracker, INotifyPropertyChanged
{
    protected List<T> removedItems;

    [DataMember]
    public List<T> RemovedItems 
    {
    get { return this.removedItems;} 
    set { this.removedItems = value;}
    }
    // Other code removed for simplification
    // ...
    //
}

It is important to understand that the RemovedItems list gets populated automatically when you remove an Item from the ObservableCollection.

Now serializing an instance of this class using the DataContractSerializer with one element in the removedItems list with the following code :

MyOwnObservableCollection<Test> _Test = new MyOwnObservableCollection<Test>();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyOwnObservableCollection<Test>));
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
string fileName = @"Test.xml";

Insurance atest = new Test();
atest.Name = @"sfdsfsdfsff";
_Test.Add(atest);
_Test.RemoveAt(0); // The Iitem in the ObservableCollection is moved to the RemovedItems List/
using (var w = XmlWriter.Create(fileName, settings))
{
    dcs.WriteObject(w, _Test);
}

ends with nothing in the XML file :

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="MyNameSpace" />

Why is this public property ignored ? What have I missed here ?

TIA.

Upvotes: 0

Views: 619

Answers (1)

metalheart
metalheart

Reputation: 3809

The problem here is that your class is derived from a collection, and as such, the DataContractSerializer serializes only its items, but not any extra properties, as stated here: No properties when using CollectionDataContract.

A workaround would be using the original (inherited) collection as a property, rather than inheriting from it:

public class MyOwnObservableCollection<T> : IDisposable
    where T : IObjectWithChangeTracker, INotifyPropertyChanged
{
   readonly ObservableCollection<T> originalCollection = new ObservableCollection<T>();
   protected List<T> removedItems = = new List<T>();

   [DataMember]
   public List<T> RemovedItems 
   {
      get { return this.removedItems;} 
      set { this.removedItems = value;}
   }

   [DataMember]
   public ObservableCollection<T> OriginalCollection  
   {
      get { return this.originalCollection; }
   }

   // ...
}

Upvotes: 2

Related Questions