Designer serialization persistence problem in .NET, Windows Forms
Posted
by Jules
on Stack Overflow
See other posts from Stack Overflow
or by Jules
Published on 2010-03-11T16:19:31Z
Indexed on
2010/03/11
18:29 UTC
Read the original article
Hit count: 419
ETA: I have a similar, smaller, problem here which, I suspect, is related to this problem.
I have a class which has a readonly property that holds a collection of components (* not quite, see below). At design time, it's possible to select from the components on the design surface to add to the collection. (Think imagelist, but instead of selecting one, you can select as many as you want.)
As a test, I inherit from button and attach my class to it as a property. The persistence problem occurs when I add a component,to the collection, from the design surface after I have added my button to the form. The best way to demonstrate this is to show you the designer generated code:
Private Sub InitializeComponent()
Dim Provider1 As WindowsApplication1.Provider = New WindowsApplication1.Provider
Me.MyComponent2 = New WindowsApplication1.MyComponent
Me.MyComponent1 = New WindowsApplication1.MyComponent
Me.MyButton1 = New WindowsApplication1.MyButton
Me.MyComponent3 = New WindowsApplication1.MyComponent
Me.SuspendLayout()
'
'MyButton1
'
Me.MyButton1.ProviderCollection.Add(Me.MyButton1.InternalProvider)
Me.MyButton1.ProviderCollection.Add(Me.MyComponent1.Provider)
Me.MyButton1.ProviderCollection.Add(Me.MyComponent2.Provider)
Me.MyButton1.ProviderCollection.Add(Provider1) //Wrong should be Me.MyComponent3.Provider
'
'Form1
'
Me.Controls.Add(Me.MyButton1)
End Sub
Friend WithEvents MyComponent1 As WindowsApplication1.MyComponent
Friend WithEvents MyComponent2 As WindowsApplication1.MyComponent
Friend WithEvents MyButton1 As WindowsApplication1.MyButton
Friend WithEvents MyComponent3 As WindowsApplication1.MyComponent
End Class
As you can see from the code, the collection is not actually a collection of the components, but a collection of a property, 'Provider', from the components.
It looks like the problem is occurring because MyComponent3
is created after MyButton
. However, in my opinion, this should not make any difference - by the time the serializer comes to add the provider property of MyComponent3
, it's already created.
Note: You may wonder, why I'm not using AddRange
to persist the collection. The reason for this is that if I do, the behaviour changes and none of the items will persist correctly. The designer will create local fields - like Provider1
- for each item in the collection.
However if I add another collection to the class which holds the actual MyComponents
and persist this, then, somehow, the AddRange
method persists correctly in ProviderCollection
!
There seems to be some kind of quantum double slit experiment going down in code dom.
How can I solve this problem?
© Stack Overflow or respective owner