Home » WPFRSS

Cannot Serialize objects from classes derived from INotifyPropertyChanged

Hi all,

this is my problem:

I have a class "Szenario" that is declared like this:

[Serializable()]
  publicclass Szenario : INotifyPropertyChanged {
   publicevent PropertyChangedEventHandler PropertyChanged;

// some code for Properties, private fields and methodsprotectedvirtualvoid OnPropertyChanged(string propertyName) {
     if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
}

 

This class creates similar classes in its constructor. It contains some Properties bound to controls by Binding. The object to serialize is a CurrentItem of an ObservableCollection<Szenario>. All Binding works flawlessly.

When trying to serialize an object of that class after it has been updated at least once in either direction thru Binding the serializer throws the exception:

 


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

The PropertyChanged delegate in fact contains a Property pointing to the EventManager mentioned in the throw-message after the first update of any bound Property.

Is there anybody who can help?

 

4 Answers Found

 

Answer 1

You should most likely flag your PropertyChanged event with [NotSerialized].

 

If the main usage is to serialize out of, back into, a WPF application, the event manager will resubscribe when the object is added back into the observable collection.

 

Answer 2

Hello Reed,

thank you for your help. I have tried the following

[NonSerialized()]
publicevent PropertyChangedEventHandler PropertyChanged;


Unfortunately the compiler does not like this construct. It diagnoses: "Error    1    Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations. "


Do you know an alternate syntax to specify the Event more like a field?

 

Answer 3

You can use [Field] attribute to your PropertyChangedEventHandler.

[Field]
publicevent PropertyChangedEventHandler PropertyChanged;


IGNOU BUZZ
ANALEC Infotech Pvt. Ltd.
 

Answer 4

Hello Reed,

thank you for your help. I have tried the following

[NonSerialized()]
publicevent PropertyChangedEventHandler PropertyChanged;


Unfortunately the compiler does not like this construct. It diagnoses: "Error    1    Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations. "


Do you know an alternate syntax to specify the Event more like a field?


Regards Uwe

Uwe,

 

With events, the syntax required is:

 

[field:NonSerialized]
publicevent PropertyChangedEventHandler PropertyChanged;

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter