VB.NET WinForm中使用Me.Controls()修改子对象属性的问题咨询
核心原因
Windows Forms的控件同一时间只能属于一个父容器的Controls集合:当你执行Checkerboard.Controls.Add(PieceArray(x))时,这些棋子控件会自动从窗体(Me)的Controls集合中移除,加入Checkerboard的Controls集合,所以后续再用Me.Controls("WR1")自然无法找到目标控件。
可行解决方案
方案1:直接从Checkerboard的Controls集合访问(性能最优)
首先确认目标控件的Name属性确实为WR1,再通过以下代码访问,增加类型转换和空校验避免报错:
If Checkerboard.Controls.ContainsKey("WR1") Then Dim wr1 As PictureBox = DirectCast(Checkerboard.Controls("WR1"), PictureBox) wr1.Location = New Point(0, 0) End If
你之前尝试的Checkerboard.Controls("WR1")未生效,大概率是没有做显式类型转换,或者未做空引用判断导致异常。
方案2:递归查找控件(不限控件所在父容器)
如果需要不绑定父容器、全局按名称查找控件,可以封装递归查找方法:
' 递归查找指定名称的控件 Private Function FindControlByName(root As Control, name As String) As Control For Each c As Control In root.Controls If c.Name = name Then Return c Dim child = FindControlByName(c, name) If child IsNot Nothing Then Return child Next Return Nothing End Function
调用方式:
Dim target As PictureBox = DirectCast(FindControlByName(Me, "WR1"), PictureBox) If target IsNot Nothing Then target.Location = New Point(0, 0) End If
方案3:复用已定义的PieceArray数组
你已经提前把所有棋子控件存入了PieceArray数组,直接操作数组元素即可,无需走控件集合查找,性能最高:
' WR1对应数组下标7,直接操作 PieceArray(7).Location = New Point(0, 0)
内容的提问来源于stack exchange,提问作者Alfie
相关产品推荐
相关产品推荐

