Reputation: 11612
I wasn't expecting to come across this error. I imagine I'm doing something wrong somewhere else.
I have an MVVM application.
My model can serialise its self using a BinaryFormatter
. This was working fine.
Today I added in an event handler to my model, and the viewmodel that contains the model subscribes to this event.
Now when I try and serialise the model I get an error because my viewmodel isn't serialisable (by design).
I am sure it's down to the subscription to the event, because I've removed the subscription (and only that) and serialisation works again.
I can't apply the [NonSerialized]
attribute to the handler because it's not a field.
It there a way around this issue?
Upvotes: 0
Views: 98
Reputation: 1280
I don't know how useful this is, but...
...extending what Pieter mentioned, you can also have mutliple delegate handlers wrapped into the same event, so you could (theoretically) make your event, in effect, both serializable and non-serializable by doing something like this:
[NonSerialized]
private EventHandler _nonSerializableeventHandler;
private EventHandler _eventHandler;
public event EventHandler MyEvent
{
add
{
if (value.Method.DeclaringType.IsSerializable)
_eventHandler += value;
else
_nonSerializableeventHandler += value;
}
remove
{
{
if (value.Method.DeclaringType.IsSerializable)
_eventHandler -= value;
else
_nonSerializableeventHandler -= value;
}
}
}
Upvotes: 0
Reputation: 3973
you can do this:
[field:NonSerialized]
public event EventHandler MyEvent;
Upvotes: 2
Reputation: 29642
You can make the event a field like this:
[NonSerialized]
private EventHandler _eventHandler;
public event EventHandler MyEvent
{
add { _eventHandler += value; }
remove { _eventHandler -= value; }
}
Upvotes: 1