将ObservableCollection保存到隔离存储

时间:2014-07-17 20:33:02

标签: c# class xaml windows-phone-8 isolatedstorage

我正在制作笔记记录应用程序,用户可以在其中创建,编辑和删除笔记。应用程序关闭后,所有数据都应存储在独立存储中。我创建了一个注释类,它在下面设置了一些属性:

    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; }

这些被放入ObservableCollection<note> GetnotesRecord(),可以使用列表框显示在主页中。触摸时有一个SelectionChange的事件处理程序,它将项目传递给编辑页面,其中可以编辑strTextContent和strNoteName等项目。

添加完所有内容后,我希望将数据保存到独立存储中,以便下次应用程序运行时加载。

是否可以保存ObservableCollection<note>?如果是,当我稍后启动应用程序时,如何从隔离存储中检索它?

1 个答案:

答案 0 :(得分:3)

步骤: -

如果你的集合很大,那么将你的ObservalbleCollection转换为xml字符串,并使用IsolatedStorageSettings类作为键值对存储它。

如果不是: - 然后你可以直接像这样

进行IsolatedStorageSettings
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();
    }

用法: -

    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"); 
相关问题