2016-07-10 26 views
1

在主窗口...从代码中的XML反序列化到我的对象精细WPF资源不能反映变化背后

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

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

回答

1

发生这种情况是因为您没有更改保存在资源字典中的实例,而是创建了一个新对象(通过反序列化)并且不保存到字典中。

这里是你应该怎么做(注意,你甚至不需要从字典读):(可能在你的代码this

var allIngredients = (Ingredients)reader.Deserialize(file); 
element.Resources["allIngredients"] = allIngredients; 
foreach (Ingredient i in allIngredients) 
{ 
    ingredientListBox.Items.Add(i); 
} 

这是假定element是在资源被发现

+0

完美,这正是我所需要的。谢谢!我尝试过'this.FindResource(“allIngredients”)= allIngredients',但没有奏效。 –