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 )? –
你为什么动态创建图片框? –
不幸的是,我不是。我现在会看看。 –