所以我在尝试更改标签的背面颜色时遇到了问题。我在学校制作的游戏中有49个标签。每个标签从 1 到 49 命名为"LabelTile1"、"LabelTile2"、"LabelTile3"等。我现在正在尝试连接玩家的分数和"标签图块"来创建例如"标签图块9"我做了很多工作,但后来我做了一个名为 LabelTileNameGenerator 的变量来存储创建的"LabelTile9"变量,然后使用 LabelTileNameGenerator.BackColor =System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
但我被告知BackColor不是字符串的成员。
有没有比为每个可能的分数一起编写 150 行代码然后点亮该磁贴更好的方法呢?'公共类 Form1 将圆形计数器调暗为整数 调暗播放器1分数为整数 将播放器2分数调暗为整数 暗淡标签磁贴名称生成器 暗淡的问候作为对象
Private Sub ButtonRollDice_Click(sender As Object, e As EventArgs) Handles ButtonRollDice.Click
Dim Rolled, Rolled2, RolledTotal As Integer
Dim oDice As New Random()
Dim Player As String
Rolled = oDice.Next(1, 7)
Rolled2 = oDice.Next(1, 7)
RolledTotal = Rolled + Rolled2
If RoundCounter Mod 2 = 0 Then
Player = 1
LabelRolledScores.Text = "Player " & Player & " got a " & Rolled & " and a " & Rolled2 & " together that gives you " & RolledTotal
Player1Score = Player1Score + RolledTotal
LabelP1Score.Text = "Player 1 current score : " & Player1Score
'.Name function used before it is set to a value
hello = "LabelTile" & Player1Score
LabelTileNameGenerator = hello
LabelTileNameGenerator.BackColor = System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
End If
If RoundCounter Mod 2 = 1 Then
Player = 2
LabelRolledScores.Text = "Player " & Player & " got a " & Rolled & " and a " & Rolled2 & " together that gives you " & RolledTotal
Player2Score = Player2Score + RolledTotal
LabelP2CurrentScore.Text = "Player 2 current score : " & Player2Score
End If
RoundCounter = RoundCounter + 1
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RoundCounter = 0
Player1Score = 1
Player2Score = 1
End Sub
结束类命名图像
图形用户界面的图像
按名称访问所有这些标签不是一个好的选择(首先使用名称创建它们也不是一个好的选择,但这是另一双鞋(。但你仍然可以这样做。您遇到的问题是您想更改标签的某些内容,但您只有标签的名称。当然,名字没有背景颜色。
你可以做这样的事情:
'We assume that this control exists and that it is a label. If you cannot assert that, you
'should add appropriate exception handling.
Dim tileLabel = CType(Me.Controls("LabelTile" & Player1Score), Label)
tileLabel.BackColor = '...
此代码段在当前窗体的控件集合中查找具有给定名称 ( "LabelTile" & Player1Score
( 的控件。返回对象的类型为 Control
。如果只想更改背景颜色,则可以保留铸件(因为Control
有BackColor
(。如果要访问特定于Label
的属性,则需要将返回的对象强制转换为类型Label
,如代码段所示。如果没有演员表,它看起来像这样:
Dim tileLabel = Me.Controls("LabelTile" & Player1Score)
tileLabel.BackColor = '...