C# WPF资源未反映来自代码隐藏的更改

C# WPF资源未反映来自代码隐藏的更改,c#,xml,wpf,serialization,C#,Xml,Wpf,Serialization,在主窗口中 Ingredients allIngredients = this.FindResource("allIngredients") as Ingredients; allIngredients = (Ingredients)reader.Deserialize(file); foreach (Ingredient i in allIngredients) { ingredientListBox.Items.Add(i); } XML反序列化到我的对象中很好,列表框中填充的项目也很

在主窗口中

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

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

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

以下是您应该如何做(注意,您甚至不需要从字典中阅读):


这假设
元素
是找到资源的地方(可能是
您的代码中的这个

完美,这正是我需要的。谢谢我尝试了
this.FindResource(“AllingCreditions”)=AllingCreditions
,但没有成功。
var allIngredients = (Ingredients)reader.Deserialize(file);
element.Resources["allIngredients"] = allIngredients;
foreach (Ingredient i in allIngredients)
{
  ingredientListBox.Items.Add(i);
}