我正在尝试序列化和反序列化这个 ObservableCollection:
public class DataCollection : ObservableCollection<Data>
{
}
public class Data : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool? _enabled;
public string Name { get; set; }
public bool? Enabled
{
get { return _enabled; }
set { _enabled = value; NotifyPropertyChanged("Enabled"); }
}
public Data(string name, bool? enabled)
{
this.ScriptName = name;
this.Enabled = enabled;
}
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
使用此类(如将对象的 Observable 集合保存到 XML 文件的最简单方法是什么?示例):
class UserPreferences
{
private DataCollection _dataLst;
private const string _dataLstFileName = "Data.xml";
public DataCollection DataLst { get { return _dataLst; } set { _dataLst = value; } }
public UserPreferences()
{
Load();
}
public void Load()
{
if (File.Exists(_dataLstFileName))
{
using (var reader = new StreamReader(_dataLstFileName))
{
var xs = new XmlSerializer(typeof(DataCollection));
_dataLst = (DataCollection) xs.Deserialize(reader);
}
}
else
{
_dataLst = new DataCollection();
}
}
public void Save()
{
using (var writer = new StreamWriter(_dataLstFileName))
{
var xs = new XmlSerializer(typeof(DataCollection));
xs.Serialize(writer, _dataLst);
}
}
}
这是我从我的应用程序中调用它的方式:
public partial class MainWindow : Window
{
private DataCollection DataLst;
...
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
var userPrefs = new UserPreferences();
userPrefs.DataLst = DataLst; // DataList isn't null and contains correct data
userPrefs.Save();
}
}
但是它会创建空文件并在行中挂断(即使没有例外,只是应用程序窗口变黑并且没有响应)
var xs = new XmlSerializer(typeof(DataCollection));