Qiqin Li
Qiqin Li

Reputation: 41

How to save an ObservableCollection?

I have an ObservableCollection like this Notes = new System.Collections.ObjectModel.ObservableCollection<Note>(); , and Note is a class:

public class Note
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public Note(string Title, string Content)
        {
            this.Title = Title;
            this.Content = Content;
        }
    }

I want to save this collection, and load it when the app starts. But when I try:

ApplicationDataContainer local = ApplicationData.Current.LocalSettings;
local.Values["notes"] = Notes;

I get an error: Error trying to serialize the value to be written to the application data store.

How can I save it?

Upvotes: 1

Views: 796

Answers (1)

Krzysztof Skowronek
Krzysztof Skowronek

Reputation: 2936

According to the docs there are constraints on the data type that you can put in the settings, collections in general are not accepted.

Your best option would be to serialize the collection for example to JSON with Newtonsoft.JSON, store a string, and then deserialize the string back to the collection.

so:

local.Values["notes"] = JsonConvert.SerializeObject(notes);

// to get the collection
observableCollection = new ObservableCollection(JsonConvert.DeserializeObject<List<Notes>>(local.Values["notes"]));

You can try to deserialize to ObservableCollection directly (change the type argument in the deserialize method), but I don't know if it would work.

Good luck :)

Upvotes: 4

Related Questions