WPF资源不反映代码背后的变化

时间:2016-07-10 05:10:38

标签: c# xml wpf serialization

在MainWindow ......

Ingredients allIngredients = this.FindResource("allIngredients") as Ingredients;
allIngredients = (Ingredients)reader.Deserialize(file);
foreach (Ingredient i in allIngredients)
{
  ingredientListBox.Items.Add(i);
}

XML反序列化到我的对象中,列表框填充项目就好了。但是,我还需要能够从MainWindow中的另一个方法访问allIngredients,当我在该方法中执行另一个FindResource时,我所拥有的只是一个空列表。我已经完成了对其他FindResource情况的测试,在这些情况下,资源反映了所做的任何更改,无论我改变它们的方法。这似乎只有在我反序列化到资源时才会发生。该对象将被填充并按预期工作,但仅限于我反序列化的方法。我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

这是因为您不更改保存在资源字典中的实例,而是创建新对象(通过反序列化)并且不将其保存到字典中。

这是你应该怎么做的(注意你甚至不需要从字典中读取):

assets/databases/myDb.db

这假定var allIngredients = (Ingredients)reader.Deserialize(file); element.Resources["allIngredients"] = allIngredients; foreach (Ingredient i in allIngredients) { ingredientListBox.Items.Add(i); } 是找到资源的位置(代码中可能是element。)