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

8

我尝试使用数据绑定将列表显示到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)
    {
        //...
    }
}

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

this.lbData.ItemsSource = myRecents;

尝试执行序列化操作

this.myRecents.Serialize(recentsPath);

出现了以下错误:

程序运行失败,错误信息如下:

程序集“WpfApplication1, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”中的类型“System.ComponentModel.PropertyChangedEventManager”未标记为可序列化。

我该怎么处理呢?

ps. 我不想对 PropertyChangedEvent 处理程序进行序列化。我想将 [NonSerializable] 属性标记到它上面,但是我不知道如何做。

1个回答

12

我想给它加上[NonSerializable]属性,但我不知道如何操作。

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

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接