简体   繁体   English

WPF 资源没有反映后面代码的变化

[英]WPF Resource not reflecting changes from code behind

In MainWindow...在主窗口...

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

The XML deserializes into my object fine, the listbox populates with the items just fine. XML 反序列化为我的对象很好,列表框填充了项目就好了。 However, I also need to be able to access allIngredients from another method inside MainWindow, and when I do another FindResource in that method, all I have is an empty list.但是,我还需要能够从 MainWindow 中的另一个方法访问 allIngredients,当我在该方法中执行另一个 FindResource 时,我所拥有的只是一个空列表。 I've done testing with other FindResource situations, and in those situations the resource reflected any changes made, no matter what method I changed them from.我已经对其他 FindResource 情况进行了测试,在这些情况下,资源反映了所做的任何更改,无论我从什么方法更改它们。 This seems to only happen when I deserialize into the resource.这似乎只发生在我反序列化到资源中时。 The object becomes populated and works as expected, but only in the method that I deserialize in. What could I be doing wrong?该对象已填充并按预期工作,但仅在我反序列化的方法中。我做错了什么?

This happens because you don't change the instance that's saved in the resource dictionary, but instead create a new object (by deserializing) and don't save it into the dictionary.发生这种情况是因为您没有更改保存在资源字典中的实例,而是创建了一个新对象(通过反序列化)并且不将其保存到字典中。

Here's how you should do it (note you don't even need to read from the dictionary):以下是您应该如何做(请注意,您甚至不需要从字典中阅读):

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

This assumes element is where the resource is found (possibly be this in your code.)这假设element是找到资源的地方(可能是您的代码中的this 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM