我有一个 XML 可序列化列表,它的类型为 ObservableCollection。我实现了一个事件,因此只要对此集合进行更改,就应该对其进行序列化,然后反序列化。
有一个外部类(武器编辑器)可以添加、删除和修改武器。只要按下删除按钮,就会来到这个 WeaponsDB 类来收集 ObservableCollection。但是,它会在我的 CollectionChanged 事件执行之前刷新 ObservableCollection 中的内容。
在任何其他类获得最新数据之前,如何确保 CollectionChanged 事件已完全执行并且一切都是最新的?
public class WeaponDatabase
{
[XmlArray("Weapons"), XmlArrayItem(typeof(Weapon), ElementName = "Weapon")]
public ObservableCollection<Weapon> Weapons = new ObservableCollection<Weapon>();
private string path = @"Inventory\WeaponsDB.xml";
public WeaponDatabase()
{
DeserializeData();
Weapons.CollectionChanged += Weapons_CollectionChanged;
}
void Weapons_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
SerializeData();
DeserializeData();
}
public void SerializeData()
{
XmlSerializer Serializer = new XmlSerializer(typeof(ObservableCollection<Weapon>));
TextWriter textWriter = new StreamWriter(path);
Serializer.Serialize(textWriter, Weapons);
textWriter.Close();
}
public void DeserializeData()
{
XmlSerializer Serializer = new XmlSerializer(typeof(ObservableCollection<Weapon>));
StreamReader reader = new StreamReader(path);
Weapons = (ObservableCollection<Weapon>)Serializer.Deserialize(reader);
reader.Close();
}
}