问题:我以编程方式生成标签但在代码中引用它们时遇到问题,因为它们在运行时不存在。
上下文:对于游戏,我已经生成了10x10标签网格,其中包含以下内容:
Public lbl As Label()
Dim tilefont As New Font("Sans Serif", 8, FontStyle.Regular)
Private Sub Lucror_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer = 0
Dim a As Integer = 0
Dim height As Integer
Dim width As Integer
height = 30
width = 30
ReDim lbl(99)
For i = 0 To 99
lbl(i) = New Label
lbl(i).Name = i
lbl(i).Size = New System.Drawing.Size(30, 30)
lbl(i).Location = New System.Drawing.Point((width), height)
lbl(i).Text = i
lbl(i).Font = tilefont
Me.Controls.Add(lbl(i))
width = width + 30
a = a + 1 'starting new line if required
If (a = 10) Then
height = height + 30
width = 30
a = 0
End If
Next
End Subenter code here
这很好用,但标签在游戏中起到了瓷砖的作用,游戏磁贴需要每个存储2-3个整数,并且能够通过事件处理程序引用。我认为存储整数的一种可能方法是生成100个数组,每个数组以一个标签命名,每个数组都保存2-3个整数,但这似乎非常多余。
我需要什么:
问题:有没有一种简单的方法可以用我生成标签的当前方式来实现这三件事(如果是这样,怎么做?)如果没有,我怎样才能生成100个标签要实现这些目标吗?
非常感谢任何帮助。
答案 0 :(得分:0)
您的标签在运行时确实存在,但在编译时不存在。附加事件在运行时略有不同,您必须使用AddHandler
。
下面是一些示例代码,应该说明您要求的所有内容。我已经将继承介绍为一种保存与每个磁贴相关的数据的方法。 GameTile
类型的行为与标签完全相同,我们添加了一些用于存储整数和命名控件的功能。
Public Class Form1
Dim tilefont As New Font("Sans Serif", 8, FontStyle.Regular)
Public Property GameTiles As List(Of GameTile)
Private Sub Lucror_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim a As Integer = 0
Dim xPosition As Integer = 30
Dim yPosition As Integer = 30
GameTiles = New List(Of GameTile)
For i = 0 To 99
Dim gt As New GameTile(i.ToString)
gt.Size = New System.Drawing.Size(30, 30)
gt.Location = New System.Drawing.Point((yPosition), xPosition)
gt.Font = tilefont
gt.Integer1 = i + 1000
gt.Integer2 = i + 2000
gt.Integer3 = i + 3000
Me.Controls.Add(gt)
AddHandler gt.Click, AddressOf TileClickHandler
GameTiles.Add(gt)
yPosition = yPosition + 30
a = a + 1 'starting new line if required
If (a = 10) Then
xPosition = xPosition + 30
yPosition = 30
a = 0
End If
Next
End Sub
Private Sub TileClickHandler(sender As Object, e As EventArgs)
Dim gt = CType(sender, GameTile)
MsgBox("This tile was clicked: " & gt.Text &
Environment.NewLine & gt.Integer1 &
Environment.NewLine & gt.Integer2 &
Environment.NewLine & gt.Integer3)
End Sub
End Class
Public Class GameTile
Inherits Label
'this class should be in a separate file, but it's all together for the sake of clarity
Public Property Integer1 As Integer
Public Property Integer2 As Integer
Public Property Integer3 As Integer
Public Sub New(NameText As String)
MyBase.New()
Name = NameText
Text = NameText
End Sub
End Class