我有一個XML序列化列表,其類型爲ObservableCollection。我實現了一個事件,以便每當對此集合進行更改時,都應該對其進行序列化,然後反序列化。C# - 檢查ObservableCollection CollectionChanged事件是否已完成執行
有一個外部類(武器編輯器),可以添加,刪除和修改武器。只要按下刪除按鈕,它就來到這個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();
}
}