Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing of Data-Bound ObservableCollection in WPF (PropertyChangedEventManager)

I tried to showed a list to Listbox by data binding. Here is my code.

[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)
    {
        //...
    }
}

It works very well basically, but when I using data binding

this.lbData.ItemsSource = myRecents;

and try to perform serialize

this.myRecents.Serialize(recentsPath);

it fails with this error:

Type 'System.ComponentModel.PropertyChangedEventManager' in Assembly 'WpfApplication1, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

How can I deal with it?

ps. I don't want to serialize a PropertyChangedEvent handler. I want to marking [NonSerializable] attribute to that, but I don't know how to that.

like image 739
mjk6026 Avatar asked Sep 10 '11 08:09

mjk6026


1 Answers

I want to marking [NonSerializable] attribute to that, but I don't know how to that.

In this case you just need to mark the event with [field:NonSerialized] attribute:

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
like image 138
Andrey Morozov Avatar answered Nov 07 '22 08:11

Andrey Morozov