Why my ObservableCollection serialization doesn't work?

后端 未结 2 758
既然无缘
既然无缘 2021-01-20 21:51

I\'m trying to serialize and deserialize this ObservableCollection:

public class DataCollection : ObservableCollection
{
}

public class Data : I         


        
相关标签:
2条回答
  • 2021-01-20 22:28

    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.

    0 讨论(0)
  • 2021-01-20 22:31
    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.
    0 讨论(0)
提交回复
热议问题