Tuesday, 27 August 2013

Don't raise OnPropertyChanged when deserializing

Don't raise OnPropertyChanged when deserializing

Let's say I have this class :
[XmlType]
public class TestModel : BindableBase
{
private int _id;
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
SetProperty(ref _id, value);
}
}
}
I am doing a lot of serialization and deserialization (from/to Json with
newtonsoft and from/to byte arrays with protobuf) and I would like to
avoid calling the SetProperty method when setting the property during the
deserialization.
Basically I would like to have something along the line with:
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
if(!serializing)
SetProperty(ref _id, value);
else
_id = value;
}
}
The reason I want to do this is because first I don't need the event
OnPropertyChanged to be raised during deserialization and secondly because
it is costly in terms of performance.
I tried using the OnDeserializing and OnDeserialized to set a flag but
while OnDeserialized lets me know when the deserialization is over
(methods decorated with OnDeserializing are not called just before the
deserialization but during the operation).
This code is in a Portable Class Library assembly so I cannot use
SerializationContext.
Any clues/hints are welcome!

No comments:

Post a Comment