PROBLEM:
I have a Child class which uses DataContractSerialization and raises a Changed event when its Name property is set.
<DataContract()>
Public Class Child
Public Event Changed()
<DataMember()>
Private _Name As String
Public Sub New(ByVal NewName As String)
_Name = NewName
End Sub
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
RaiseEvent Changed()
End Set
End Property
End Class
It is contained within a Parent class which also uses DataContractSerialization and handles the Changed event of the Child.
<DataContract()>
Public Class Parent
<DataMember()>
Private WithEvents Child As Child
Private Sub Child_Changed() Handles Child.Changed
'Handle changed event here...
End Sub
End Class
The Parent class is serialzed and deserialized and all the data (including the Child) is saved and resored as expected.
However, after deserialization, the Changed event is never raised!
QUESTIONS:
I know the deserialization process bypasses class constructors, but shouldn't the event be initialized?
Am I doing something wrong?
Is it possible to serialize/deserialize the Event?
Is there a better workaround than the following (see below)?
Is there a way to initialize the event in the OnDeserialzed method of the Child rather than the Parent (see below)?
WORKAROUND:
(1) Add a constructor to the Child class which takes an instance of itself as an argument.
(2) Add an OnDeserialized method to the Parent class which creates a New instance of the Child class based on the deserialzed instance of the Child class.
<OnDeserialized()>
Private Sub OnDeserializedMethod(ByVal Context As StreamingContext)
Child = New Child(Child)
End Sub
Now the Changed event is raised as expected.