3

I'm trying to serialize and deserialize this ObservableCollection:

public class DataCollection : ObservableCollection<Data>
{
}

public class Data : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool? _enabled;

    public string Name { get; set; }
    public bool? Enabled 
    {
        get { return _enabled; }
        set { _enabled = value; NotifyPropertyChanged("Enabled"); }
    }

    public Data(string name, bool? enabled)
    {
        this.ScriptName = name;
        this.Enabled = enabled;
    }

    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

Using this class (as in the What is the easiest way to save an Observable collectin of object to an XML file? example):

class UserPreferences
{
    private DataCollection _dataLst;
    private const string _dataLstFileName = "Data.xml";

    public DataCollection DataLst { get { return _dataLst; } set { _dataLst = value; } }

    public UserPreferences()
    {
        Load();
    }

    public void Load()
    {
        if (File.Exists(_dataLstFileName))
        {
            using (var reader = new StreamReader(_dataLstFileName))
            {
                var xs = new XmlSerializer(typeof(DataCollection));
                _dataLst = (DataCollection) xs.Deserialize(reader);
            }
        }
        else
        {
            _dataLst = new DataCollection();
        }
    }

    public void Save()
    {
        using (var writer = new StreamWriter(_dataLstFileName))
        {
            var xs = new XmlSerializer(typeof(DataCollection));
            xs.Serialize(writer, _dataLst);
        }
    }
}

And here is how I call it from my app:

public partial class MainWindow : Window
{
    private DataCollection DataLst;

    ...

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        var userPrefs = new UserPreferences();

        userPrefs.DataLst = DataLst; // DataList isn't null and contains correct data
        userPrefs.Save(); 
    }
}

But it creates empty file and hangs up (even without exceptions, just app window becomes black and doesn't response) in the line

var xs = new XmlSerializer(typeof(DataCollection));  
2
  • Add [Serializable] to your DataCollection
    – nemesv
    Sep 1, 2012 at 7:47
  • @nemesv it doesn't help, still the same problem.
    – Alex P.
    Sep 1, 2012 at 7:56

2 Answers 2

5

After a little research it seems that there are problems when serializing ObservableCollection<T>. See this blog post for more information.

In summary:

The problem is that the events have not been marked as non-serialized. Therefore, whenever you try to serialize an instance of ObservableCollection, you will also be attempting to serialize any event handlers. When you're using the collection for its primary scenario (data binding), you will have WPF controls attached to the events.

(Kent Boogaart)

Your Data class will also suffer from similar problems; update your PropertyChanged event like so:

[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

As well as the updates already mentioned by other people, your Data class should also be marked as Serializable.

4
  • I have read somewhere that events issue was fixed in .NET 4.0. Looks like it works when I add parameter less constructor to Data class.
    – Alex P.
    Sep 1, 2012 at 8:24
  • I will leave this answer here as this may help someone using an earlier version of the framework. Your data class will will still need to have its property changed event updated as suggested though otherwise it will also be trying to serialize anything that is subscribed. Sep 1, 2012 at 8:28
  • 2
    April 2016 - Just confirming this is not an issue in current .NET - ObservableCollection<T> is serializable with no special handling required. Even works in a PCL project in a Xamarin.Forms cross-platform solution. Apr 18, 2016 at 18:51
  • Is there any difference between [Serializable] and [Serializable()] ?
    – sergiol
    Apr 23, 2021 at 13:22
3
  1. Your Data class must have a parameter less constructor, otherwise XmlSerializer will never be able to create instance of Data.
  2. Instead of storing DataCoollection, you should store and retrieve Data[], it's easier without having to do anything else.
  3. While storing, you can call ToArray method to get Data[] and use typeof(Data[]) for serializer.
  4. While reading you can read the array and add items into your collection.
2
  • Thank you, looks like it works after I added a parameter less constructor. But what do you mean that I should "store and retrieve Data[] instead of storing DataCollection? Why it is easier? I'm using ObservableCollection as a ListBox ItemsSource binding (WPF).
    – Alex P.
    Sep 1, 2012 at 8:29
  • Sometimes we had issues and it did require extra coding, I dont remember exactly what were the problems but we avoided serializing collection and we always serialized as arrays. Because serialized arrays are easily accessible in older version of .NET as well.
    – Akash Kava
    Sep 1, 2012 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.