我正在尝试将自定义类型的ObservableCollection保存到我的wp8应用程序中的独立存储中。可观察的集合保存类型BitmapImage和字符串的值。这样做的目的是从CameraCaptureTask结果中保存图像及其各自的名称。如何序列化ObservableCollection的自定义类型
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;
}
位置设置为我宣布举行命名的ImageList观察集合类,并imgList是,是的ObservableCollection绑定到一个列表框。
Settings.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;
}
}
此外,观察到的集合的类型的ImageItem,其是如下
ImageItem.cs
public class ImageItem
{
public BitmapImage ImageUri
{
get;
set;
}
public string ImageName
{
get;
set;
}
}
出于某种原因,虽然在应用正在运行的图片保存在imageList集合中,并填充到imgList列表框中,但是当应用程序关闭并重新启动时,observablecollection是空的?我相信BitmapImage是问题(它不是序列化?),我无法得到可观察的集合保存CameraCaptureTask的图像?
你可以加载你的加载/保存代码到你的问题?这似乎是问题的根源... – 2013-03-15 01:22:39
根据我的经验,ObservableCollection应该与列表没有任何不同。我怀疑问题出在你的保存/加载方法之间,或者你的ImageItem类不能被序列化。对不起,以前从未尝试序列化BitmapImage,所以我怀疑它。 –
Fendy
2013-03-15 01:44:33
是的,我相信BitmapImage的这些串行化或保存/加载方法是问题的根源,但我不确定如何解决此问题。我在上面的问题中添加了名为'Setting.cs'的保存/加载方法。 – Matthew 2013-03-15 01:46:53