Search code examples
c#classxamlwindows-phone-8isolatedstorage

Saving ObservableCollection to isolated storage


I am in the process of making a note taking app, in which the user can create, edit and delete notes. Once the app is closed all data should be stored in isolated storage. I have created a note class which sets some properties below:

    public string strNoteName { get; set; }
    public string strCreated { get; set; }
    public string strModified { get; set; }
    public bool boolIsProtected { get; set; }
    public string strNoteImage { get; set; }
    public string strNoteSubject { get; set; }
    public string strTextContent { get; set; }

These are put into an ObservableCollection<note> GetnotesRecord() which can be displayed in the Mainpage using a listbox. On touch there is an event handler for SelectionChange which passes the item to the editpage where items such as strTextContent and strNoteName can be edited.

After adding all this, I want the data to be saved to isolated storage so it can be loaded next time the app runs.

Is it possible to save an ObservableCollection<note>? If yes, how can it be retrieved from the isolated storage when I'm starting the app later?


Solution

  • Steps :-

    If you collection is big then convert your ObservalbleCollection to a xml string and store it using IsolatedStorageSettings class as a Key-Value pair.

    If it is not :- then you can IsolatedStorageSettings directly like this

    IsolatedStorageSettings Store { get { return IsolatedStorageSettings.ApplicationSettings; } }
    
        public T GetValue<T>(string key)
        {
            return (T)Store[key];
        }
    
        public void SetValue(string token, object value)
        {
            Store.Add(token, value);
            Store.Save();
        }
    

    Usage :-

        ObservableCollection<Note> objCollection = new ObservableCollection<Note>()
        {
            new Note(){Checkbool = false,Checkme = "sd"},
            new Note(){Checkbool = false,Checkme = "sd1"},
            new Note(){Checkbool = false,Checkme = "sd2"}
        };
    
        // you can also make check whether values are present or 
        // by checking the key in storage.
        var isContainKey = Store.Contains("set")
    
        // save key value pair
        SetValue("set", objCollection); 
    
        // extract key value pair
        var value = GetValue<ObservableCollection<Note>>("set");