我正在尝试将自定义类型的 ObservableCollection 保存到我的 wp8 应用程序中的隔离存储中。observable 集合包含 BitmapImage 和字符串类型的值。这样做的目的是从 CameraCaptureTask 结果中保存图像及其各自的名称。
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//clear current values if any
imgChosenPhotoFileName = null;
bmp = new BitmapImage();
imgChosenPhotoFileName = e.OriginalFileName;
//Display the photo on the page
bmp.SetSource(e.ChosenPhoto);
imgChosenPhoto.Source = bmp;
//Add photo info to Recent
AddToImgList(imgChosenPhotoFileName, bmp);
}
}
private void AddToImgList(string fileName, BitmapImage bitmap)
{
Settings.imageList.Value.Add(new ImageItem() { ImageName = fileName, ImageUri = bitmap });
//Settings.imageList.Value.Add(bitmap);
//populate the List with the saved imageList
imgList.ItemsSource = Settings.imageList.Value;
}
其中 Settings 是我已声明保存名为 imageList 的 observable 集合的类,而 imgList 是 observablecollection 绑定到的 Listbox。
设置.cs
public static class Settings
{
public static readonly Setting<ObservableCollection<ImageItem>> imageList = new Setting<ObservableCollection<ImageItem>>("imageList", new ObservableCollection<ImageItem>());
}
Setting 是从隔离存储中保存和加载数据的类。
设置.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;
}
}
另外,observable集合是ImageItem类型的,如下
图像项.cs
public class ImageItem
{
public BitmapImage ImageUri
{
get;
set;
}
public string ImageName
{
get;
set;
}
}
出于某种原因,虽然应用程序运行时图片保存在imageList集合中并填充到imgList Listbox中,但是当应用程序关闭并重新启动时,observablecollection为空?我相信 BitmapImage 是问题(它没有序列化?),我无法获得可观察的集合来保存来自 CameraCaptureTask 的图像?