我在我的IsolatedStorageSettingsObservableCollection<Recipe>
中保存了一个JSON字符串。
该类Recipe
有一个Category
由以下代码初始化的名为的字段:
[JsonProperty]
private Category _category = RecipesViewModel.BaseCategories.First();
ACategory
是这样的:
[JsonProperty]
public Categories BaseCategory;
/// <summary>
/// Background picture for the cagtegory
/// </summary>
public string Picture
{
get { return string.Format(@"/Assets/CategoriesPictures/{0}.jpg", BaseCategory); }
}
/// <summary>
/// Category's name
/// </summary>
public string Name
{
get { return BaseCategory.ToString(); }
}
/// <summary>
/// List of recipes that belong to this category
/// </summary>
public IEnumerable<Recipe> Recipes
{
get { return App.ViewModel.GetRecipesByCategory(this); }
}
/// <summary>
/// We need this to let everyone know that something may have been changed in our collections
/// </summary>
public void UpdateCategory()
{
RaisePropertyChanged(() => Recipes);
}
BaseCategory
一个简单的枚举在哪里
public enum Categories
{
Breakfast,
Lunch,
Appetizer,
Sidedish,
Soup,
Dessert,
Beverages
}
目前我只有一个Recipe
,ObservableCollection<Recipe>
这是保存在IsolatedStorageSettings中的JSON:
[
{
"_addedDate": "2013-11-10T19:08:00.8968706+01:00",
"_category": {
"BaseCategory": 2
},
"_ingredients": [],
"_recipeName": "recipeName",
"_steps": [],
"_temperature": 0.0
}
]
被BaseCategories
声明为
public static ReadOnlyCollection<Category> BaseCategories { get; private set; }
它是通过这种方法构建的:
private static void BuildCategories()
{
var categories = new ObservableCollection<Category>();
foreach (var enumValue in from category in typeof(Categories).GetFields()
where category.IsLiteral
select (Categories)category.GetValue(typeof(Categories)))
{
categories.Add(new Category { BaseCategory = enumValue });
}
BaseCategories = new ReadOnlyObservableCollection<Category>(categories);
}
发生的情况是,在我的数据加载方法中,第一个元素BaseCategories
变成了JSONCategory
中写入的元素。
在这种情况下,它从早餐变成了开胃菜(这是Category
唯一保存的Recipe
)。
这是我用来加载数据的代码:
public void LoadData()
{
if (BaseCategories.IsEmpty())
BuildCategories();
// Load data from IsolatedStorage
var jsonString = "";
if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(RecipesKey, out jsonString))
{
// BEFORE THIS LINE EVERYTHING IS FINE
Recipes = JsonConvert.DeserializeObject<ObservableCollection<Recipe>>(jsonString);
// AFTER THIS LINE, THE FIRST CATEGORY IN BaseCategories IS CHANGED
}
UpdateCategories();
IsDataLoaded = true;
}
有谁知道那里发生了什么?
我整天都在处理这个代码,所以我的头现在已经消失了!