IsolatedStorage 在应用重启 WP7 后不保存列表 <MyObject>
IsolatedStorage not saving List<MyObject> after app restart WP7
我正在开发一个应用程序,我需要在其中保存 ExerciseObject 类型的对象列表。我不明白为什么在应用程序重新启动后此数据没有保留在 IsolatedStorageSettings 中,而我的所有其他数据(包括我创建的其他对象)。
这是 ExerciseObject class,我在其中创建了一个列表,其中包含要存储到 IsolatedStorageSettings 的此对象类型。有趣的是,当应用程序打开时,数据被保存了,只是一旦我重新启动应用程序,只有 ExerciseObject 数据列表丢失了。
public class ExerciseObject
{
public ExerciseObject(string description, int caloriesBurned, bool burned)
{
this.Description = description;
this.CaloriesBurned = caloriesBurned;
this.Burned = burned; // true if activity, false if food
if (this.Burned) // text should be green
this.TextColor = new SolidColorBrush(Colors.Green);
else
this.TextColor = new SolidColorBrush(Colors.Red);
}
public string Description { get; set; }
public int CaloriesBurned { get; set; }
public bool Burned { get; set; }
public SolidColorBrush TextColor { get; set; }
}
这就是我添加到列表中的方式:
ExerciseObject exerciseObj = new ExerciseObject(this.txtActivity.Text, int.Parse(this.txtBurned.Text), true);
List<ExerciseObject> tempList = (List<ExerciseObject>)IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"];
tempList.Add(exerciseObj);
IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"] = tempList;
这就是我访问列表的方式:
// Get the list of exercise objects from the isolated storage
List<ExerciseObject> exerciseObjects = (List<ExerciseObject>)IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"];
// Setting data context of listBox to the list of exercise objects for now
this.listBoxEntries.DataContext = exerciseObjects;
我试过你的例子,SolidColorBrush 类型似乎不可序列化。当应用程序存在时,phone 内部调用 iso storage "Save" 方法,但它会静默失败。要重现,删除 TextColor 属性 或在 属性 上应用 "IgnoreDataMemberAttribute" 并观察问题是否消失。
有多种方法可以解决这个问题。我个人会从您的 "burned" 属性 中推导出在运行时应用的画笔类型。
我附上了您的代码的工作示例,如果您仍然希望存储它,它现在存储实际颜色而不是 SolidColorBrush 对象。
Main.cs
// Constructor
public MainPage()
{
InitializeComponent();
BindExercises();
}
private void AddExercise(object sender, RoutedEventArgs e)
{
var exercise = new ExerciseObject("Activity added at: " + DateTime.Now.Ticks, (DateTime.Now.Second + 200), true);
IsolatedStorageSettingsManager.AddToCollection("ListExerciseObjects", exercise);
this.BindExercises();
}
private void BindExercises()
{
// Setting data context of listBox to the list of exercise objects for now
this.listBoxEntries.ItemsSource = IsolatedStorageSettingsManager.Get<IEnumerable<ExerciseObject>>("ListExerciseObjects").ToObservableCollection();
}
private void RemoveAllExercises(object sender, RoutedEventArgs e)
{
IsolatedStorageSettingsManager.Remove("ListExerciseObjects");
this.BindExercises();
}
public static class EnumerableExtensions
{
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> myList)
{
if (myList == null) return null;
var oc = new ObservableCollection<T>();
foreach (var item in myList)
oc.Add(item);
return oc;
}
}
public class ExerciseObject
{
public ExerciseObject() { }
public ExerciseObject(string description, int caloriesBurned, bool burned)
{
this.Description = description;
this.CaloriesBurned = caloriesBurned;
this.Burned = burned; // true if activity, false if food
if (this.Burned) // text should be green
this.Color = Colors.Green;
else
this.Color = Colors.Red;
}
public string Description { get; set; }
public int CaloriesBurned { get; set; }
public bool Burned { get; set; }
public Color Color { get; set; }
[IgnoreDataMemberAttribute]
public SolidColorBrush TextColor
{
get
{
return new SolidColorBrush(this.Color);
}
}
}
public class IsolatedStorageSettingsManager
{
private static readonly IsolatedStorageSettings isolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings;
public static void Add<T>(string key, T value)
{
if (isolatedStorageSettings.Contains(key))
{
isolatedStorageSettings[key] = value;
}
else
{
isolatedStorageSettings.Add(key, value);
}
Save();
}
public static T Get<T>(string key, T @default = default(T))
{
T value;
if (isolatedStorageSettings.TryGetValue(key, out value))
{
return value;
}
return @default; // TODO: tell it what to do if the key is not found.
}
/// <summary>
/// Special [very crude] method which handles collections.
/// </summary>
/// <typeparam name="T">
/// The type of object to be serialized.
/// </typeparam>
/// <param name="key">
/// The key to assign to the object.
/// </param>
/// <param name="newValue">
/// The new record to add.
/// </param>
/// <returns>
/// The newly updated collection.
/// </returns>
public static IEnumerable<T> AddToCollection<T>(string key, T newValue) where T : class
{
List<T> currentValues;
if (isolatedStorageSettings.Contains(key))
{
currentValues = isolatedStorageSettings[key] as List<T>;
if (currentValues == null)
{
throw new InvalidCastException("The current values in the isolated storage settings " + key + "is not of a valid type");
}
currentValues.Add(newValue);
isolatedStorageSettings[key] = currentValues;
}
else
{
currentValues = new List<T> { newValue };
isolatedStorageSettings.Add(key, currentValues);
}
Save();
return currentValues;
}
public static void Remove(string key)
{
if (isolatedStorageSettings.Contains(key))
{
isolatedStorageSettings.Remove(key);
Save();
}
}
private static void Save()
{
isolatedStorageSettings.Save();
}
}
Xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add Exercise" Click="AddExercise" />
<Button Grid.Row="1" Content="Clear All" Click="RemoveAllExercises" />
<ListBox x:Name="listBoxEntries" Grid.Row="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Description }" />
<TextBlock Margin="15 0 0 0" Text="{Binding CaloriesBurned }" Foreground="{Binding TextColor}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
我正在开发一个应用程序,我需要在其中保存 ExerciseObject 类型的对象列表。我不明白为什么在应用程序重新启动后此数据没有保留在 IsolatedStorageSettings 中,而我的所有其他数据(包括我创建的其他对象)。
这是 ExerciseObject class,我在其中创建了一个列表,其中包含要存储到 IsolatedStorageSettings 的此对象类型。有趣的是,当应用程序打开时,数据被保存了,只是一旦我重新启动应用程序,只有 ExerciseObject 数据列表丢失了。
public class ExerciseObject
{
public ExerciseObject(string description, int caloriesBurned, bool burned)
{
this.Description = description;
this.CaloriesBurned = caloriesBurned;
this.Burned = burned; // true if activity, false if food
if (this.Burned) // text should be green
this.TextColor = new SolidColorBrush(Colors.Green);
else
this.TextColor = new SolidColorBrush(Colors.Red);
}
public string Description { get; set; }
public int CaloriesBurned { get; set; }
public bool Burned { get; set; }
public SolidColorBrush TextColor { get; set; }
}
这就是我添加到列表中的方式:
ExerciseObject exerciseObj = new ExerciseObject(this.txtActivity.Text, int.Parse(this.txtBurned.Text), true);
List<ExerciseObject> tempList = (List<ExerciseObject>)IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"];
tempList.Add(exerciseObj);
IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"] = tempList;
这就是我访问列表的方式:
// Get the list of exercise objects from the isolated storage
List<ExerciseObject> exerciseObjects = (List<ExerciseObject>)IsolatedStorageSettings.ApplicationSettings["ListExerciseObjects"];
// Setting data context of listBox to the list of exercise objects for now
this.listBoxEntries.DataContext = exerciseObjects;
我试过你的例子,SolidColorBrush 类型似乎不可序列化。当应用程序存在时,phone 内部调用 iso storage "Save" 方法,但它会静默失败。要重现,删除 TextColor 属性 或在 属性 上应用 "IgnoreDataMemberAttribute" 并观察问题是否消失。
有多种方法可以解决这个问题。我个人会从您的 "burned" 属性 中推导出在运行时应用的画笔类型。
我附上了您的代码的工作示例,如果您仍然希望存储它,它现在存储实际颜色而不是 SolidColorBrush 对象。
Main.cs
// Constructor
public MainPage()
{
InitializeComponent();
BindExercises();
}
private void AddExercise(object sender, RoutedEventArgs e)
{
var exercise = new ExerciseObject("Activity added at: " + DateTime.Now.Ticks, (DateTime.Now.Second + 200), true);
IsolatedStorageSettingsManager.AddToCollection("ListExerciseObjects", exercise);
this.BindExercises();
}
private void BindExercises()
{
// Setting data context of listBox to the list of exercise objects for now
this.listBoxEntries.ItemsSource = IsolatedStorageSettingsManager.Get<IEnumerable<ExerciseObject>>("ListExerciseObjects").ToObservableCollection();
}
private void RemoveAllExercises(object sender, RoutedEventArgs e)
{
IsolatedStorageSettingsManager.Remove("ListExerciseObjects");
this.BindExercises();
}
public static class EnumerableExtensions
{
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> myList)
{
if (myList == null) return null;
var oc = new ObservableCollection<T>();
foreach (var item in myList)
oc.Add(item);
return oc;
}
}
public class ExerciseObject
{
public ExerciseObject() { }
public ExerciseObject(string description, int caloriesBurned, bool burned)
{
this.Description = description;
this.CaloriesBurned = caloriesBurned;
this.Burned = burned; // true if activity, false if food
if (this.Burned) // text should be green
this.Color = Colors.Green;
else
this.Color = Colors.Red;
}
public string Description { get; set; }
public int CaloriesBurned { get; set; }
public bool Burned { get; set; }
public Color Color { get; set; }
[IgnoreDataMemberAttribute]
public SolidColorBrush TextColor
{
get
{
return new SolidColorBrush(this.Color);
}
}
}
public class IsolatedStorageSettingsManager
{
private static readonly IsolatedStorageSettings isolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings;
public static void Add<T>(string key, T value)
{
if (isolatedStorageSettings.Contains(key))
{
isolatedStorageSettings[key] = value;
}
else
{
isolatedStorageSettings.Add(key, value);
}
Save();
}
public static T Get<T>(string key, T @default = default(T))
{
T value;
if (isolatedStorageSettings.TryGetValue(key, out value))
{
return value;
}
return @default; // TODO: tell it what to do if the key is not found.
}
/// <summary>
/// Special [very crude] method which handles collections.
/// </summary>
/// <typeparam name="T">
/// The type of object to be serialized.
/// </typeparam>
/// <param name="key">
/// The key to assign to the object.
/// </param>
/// <param name="newValue">
/// The new record to add.
/// </param>
/// <returns>
/// The newly updated collection.
/// </returns>
public static IEnumerable<T> AddToCollection<T>(string key, T newValue) where T : class
{
List<T> currentValues;
if (isolatedStorageSettings.Contains(key))
{
currentValues = isolatedStorageSettings[key] as List<T>;
if (currentValues == null)
{
throw new InvalidCastException("The current values in the isolated storage settings " + key + "is not of a valid type");
}
currentValues.Add(newValue);
isolatedStorageSettings[key] = currentValues;
}
else
{
currentValues = new List<T> { newValue };
isolatedStorageSettings.Add(key, currentValues);
}
Save();
return currentValues;
}
public static void Remove(string key)
{
if (isolatedStorageSettings.Contains(key))
{
isolatedStorageSettings.Remove(key);
Save();
}
}
private static void Save()
{
isolatedStorageSettings.Save();
}
}
Xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add Exercise" Click="AddExercise" />
<Button Grid.Row="1" Content="Clear All" Click="RemoveAllExercises" />
<ListBox x:Name="listBoxEntries" Grid.Row="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Description }" />
<TextBlock Margin="15 0 0 0" Text="{Binding CaloriesBurned }" Foreground="{Binding TextColor}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>