我一直在使用一个辅助类,它使用键值对从隔离存储中保存和检索值。这适用于在我的应用程序中更改的单个值,但我现在尝试将它用于 ObservableCollection,其中将在运行时添加和删除项目。出于某种原因,当应用程序关闭并重新打开时,我的 ObservableCollection 不会从 IsolatedStorage 中存储和/或检索。我不确定我做错了什么,因为这适用于个人价值观吗?
设置.cs
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
//Check for the cached value
if (!this.hasValue)
{
//Try to get the value from Isolated Storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
{
//It hasn't been set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
//Save the value to Isolated Storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
// Clear cached value
public void ForceRefresh()
{
this.hasValue = false;
}
}
上面的 Setting.cs 类用于存储和检索值,我正在使用另一个名为 Settings.cs 的类作为使用这些存储值的机制。
设置.cs
public static Setting<ObservableCollection<BrowserItem>> BrowserList = new Setting<ObservableCollection<BrowserItem>>("Browsers", new ObservableCollection<BrowserItem>());
public static Setting<string> InitialUri = new Setting<string>("InitialUri", "http://www.bing.com");
在上面,InitialUri
可以更改并且正确保存和检索值。另一方面,BrowserList
(BrowserItem 类型的 ObservableCollection(自定义类))没有存储或保存?以下显示了我如何尝试使用BrowserList
浏览器项.cs
[DataContract]
public class BrowserItem
{
[DataMember]
public FullWebBrowser Browser
{
get;
set;
}
[DataMember]
public string Url
{
get;
set;
}
[DataMember]
public BitmapImage ImageUri
{
get;
set;
}
[DataMember]
public string Title
{
get;
set;
}
[DataMember]
public string Notification
{
get;
set;
}
[DataMember]
public bool DisplayNotification
{
get
{
return !string.IsNullOrEmpty(this.Notification);
}
}
[DataMember]
public string Message
{
get;
set;
}
[DataMember]
public string GroupTag
{
get;
set;
}
[DataMember]
//for translation purposes (bound to HubTile Title on MainPage)
public string TileName
{
get;
set;
}
}
TabsPage.xaml.cs
void addNew_Click(object sender, EventArgs e)
{
BitmapImage newTileImage = new BitmapImage();
var newItem = new BrowserItem() { Browser = new FullWebBrowser(), Url = "http://www.bing.com", ImageUri = newTileImage, Title = "new", /*Notification = "",*/ Message = "new browser", GroupTag = "TileGroup", TileName = "new" };
newItem.Browser.InitialUri = Settings.InitialUri.Value; //set the initial uri when created
Settings.BrowserList.Value.Add(newItem); //update saved BrowserList
}
在addNew_Click
偶数处理程序中,成功添加了新的BrowserItem
命名。newItem
但是,当应用程序关闭或重新打开时,我会检查BrowserList
项目是否存在,如果存在,我想根据 ObservableCollection 中的项目索引值加载特定的项目。每次我执行检查,BrowserList
有没有保存的项目?如何正确地将这些值保存在集合中,以便它们持续存在?