Serialing控件的小集合並不困難。如果項目已有數據庫,則可以使用該數據庫。
第一個問題是控件無法直接序列化。你需要一個類來保存重建他們所需要的數據:
<Serializable>
Friend Class CtlItem
Public Property Location As Point
Public Property Size As Size
Public Property BackColor As Color
Public Property Text As String
' some serializers require a simple ctor
Public Sub New()
End Sub
' create object from passed PB
Public Sub New(pb As Button)
Location = pb.Location
Size = pb.Size
BackColor = pb.BackColor
Text = pb.Text
End Sub
End Class
我使用按鈕代替pictureboxes的,但概念是相同的。許多序列化器需要<Serializable>
屬性和一個簡單的ctor。我沒有把所有的道具放在代碼中,而是讓班級收穫我需要保存的道具。您需要將其擴展爲保存控件的所有非默認屬性。
獲得數據,序列化和測試往返:
' collection for many control descriptors
Dim btns As New List(Of CtlItem)
' collect the data for some controls
For Each btn In TabPage1.Controls.OfType(Of Button)()
btns.Add(New CtlItem(btn))
Next
' serialize the list
Using fs As New FileStream("C:\Temp\Buttons.bin", FileMode.OpenOrCreate)
fs.Position = 0
Dim bf As New BinaryFormatter
bf.Serialize(fs, btns)
End Using
' round trip test
Dim newBtns As List(Of CtlItem)
Using fs As New FileStream("C:\Temp\Buttons.bin", FileMode.Open)
Dim bf As New BinaryFormatter
newBtns = CType(bf.Deserialize(fs), List(Of CtlItem))
End Using
它使用BinaryFormatter
序列化,但XMLSerialzer,protobuf網和JSON所有的工作幾乎相同。最初的集合有19個按鈕,第一個是「文件」。圖像顯示newBtns
colelction具有相同的數字,並且至少第一個匹配(序列化通常是全部或全部命題)。該btns
收集,前:
的newBtns
收集後:
您的代碼將然後從該數據重新創建控件並將其添加到窗體。如果它們來自不同的Control
集合並且當然還原圖像,這可能變得複雜。核心代碼可能是在CtlItem
類:
Friend Function NewButton() As Button
Dim btn As New Button
btn.Location = Location
btn.Text = Text
btn.BackColor = BackColor
'...
Return btn
End Function
你熟悉[連載](https://msdn.microsoft.com/en-us/library/ms973893.aspx?f=255&MSPPError=-2147217396 )? –
你爲什麼動態創建圖片框? –
不幸的是,我不是。我現在會看看。 –