在我的应用中,我需要保留一些数据。到目前为止,使用内置字典并保留原始类型没有问题。当我想保存ObservableCollection时,问题就开始了。根据{{3}},这是可能的(第3部分。数据持久性)。在我的应用中,我使用了以下代码:
if (!App.Current.Properties.ContainsKey("phist"))
{
App.Current.Properties.Add("phist", DataBase.phist);
App.Current.SavePropertiesAsync();
}
else
{
App.Current.Properties["phist"] = DataBase.phist;
App.Current.SavePropertiesAsync();
}
(DataBase是我用于在应用程序页面之间发送数据的静态类)
使用上面的代码,我保存了DataBase.phist ObservableCollection(带有字符串)。但是,当我重新启动应用程序并尝试获取数据时,没有像“ phist”这样的键
ObservableCollection<string> temp_coll = new ObservableCollection<string>();
Console.WriteLine(temp_coll.Count);
if (App.Current.Properties.ContainsKey("phist"))
{
temp_coll = App.Current.Properties["phist"] as ObservableCollection<string>;
for (int i = 0; i < temp_coll.Count; i++)
{
DataBase.phist.Add(temp_coll[i]);
Console.WriteLine("temp collection no " + i + ": " + temp_coll[i]);
Console.WriteLine("phist collection no " + i + ": " + DataBase.phist[i]);
}
}
else
Console.WriteLine("No such key");
控制台上的输出为“无此键”。 当我尝试在不关闭应用程序的情况下读取保存的数据时,查找或读取密钥没有任何问题,但是在输出中,我有数千行(temp_coll.Count等于1或2)。
总结一下我的问题:是否可以将整个ObservableCollection保留在内置字典中?如果是,怎么办?如果不可能的话,还有什么其他解决方案可以保存呢?
谢谢。