在WPF中序列化数据绑定的ObservableCollection(PropertyChangedEventManager)

mjk*_*026 8 wpf serialization

我试图通过数据绑定向Listbox显示一个列表.这是我的代码.

[Serializable]
public class RecordItem : INotifyPropertyChanged
{
    //implements of INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify(string propName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } }
}


[Serializable]
public class Records : ObservableCollection<RecordItem>
{
    public UOCRecords() { }

    public void Serialize(string path)
    {
        BinaryFormatter binForm = new BinaryFormatter();
        using (FileStream sw = File.Create(path))
        {
            binForm.Serialize(sw, this);
            sw.Close();
        }
    }

    public static UOCRecords Deserialize(string path)
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上它工作得很好,但是当我使用数据绑定时

this.lbData.ItemsSource = myRecents;
Run Code Online (Sandbox Code Playgroud)

并尝试执行序列化

this.myRecents.Serialize(recentsPath);
Run Code Online (Sandbox Code Playgroud)

它失败并出现此错误:

在Assembly'WpfApplication1,Version = 3.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35'中键入'System.ComponentModel.PropertyChangedEventManager'未标记为可序列化.

我怎么处理它?

PS.我不想序列化PropertyChangedEvent处理程序.我想将[NonSerializable]属性标记为,但我不知道如何.

And*_*zov 12

我想将[NonSerializable]属性标记为,但我不知道如何.

在这种情况下,您只需要使用[field:NonSerialized]属性标记事件:

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
Run Code Online (Sandbox Code Playgroud)