简体   繁体   中英

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM