.net 如何在窗体及其嵌套面板中查找标签控件?
我需要更改窗体和嵌套面板内所有标签的背景色。.net 如何在窗体及其嵌套面板中查找标签控件?,.net,vb.net,winforms,.net,Vb.net,Winforms,我需要更改窗体和嵌套面板内所有标签的背景色。 For Each Label As Control In Me.Controls If Label.GetType.ToString = "System.Windows.Forms.panel" Then Label.BackColor = Color.AliceBlue End If Next 我尝试了此代码,但它只更改表单中标签的颜色,而不是面板中的所有标签。 For Each Label
For Each Label As Control In Me.Controls
If Label.GetType.ToString = "System.Windows.Forms.panel" Then
Label.BackColor = Color.AliceBlue
End If
Next
我尝试了此代码,但它只更改表单中标签的颜色,而不是面板中的所有标签。 For Each Label As Control In Me.Controls
If Label.GetType.ToString = "System.Windows.Forms.panel" Then
Label.BackColor = Color.AliceBlue
End If
Next
我的表单如下所示:
您可以设置一个简单的递归方法来解析表单中的所有控件。
当集合中的控件类型为
Label
时,设置BackColor
属性。当控件包含其他控件时,解析其
控件
集合以查看它是否包含一些标签;找到一个后,设置其背景色
调用方法:
SetLabelsColor(Me, Color.AliceBlue)
Private Sub SetLabelsColor(parent As Control, color As Color)
If (parent Is Nothing) OrElse (Not parent.HasChildren) Then Return
For Each ctl As Control In parent.Controls.OfType(Of Control)
If TypeOf ctl Is Label Then
ctl.BackColor = color
Else
If ctl.HasChildren Then
SetLabelsColor(ctl, color)
End If
End If
Next
End Sub
递归方法:
SetLabelsColor(Me, Color.AliceBlue)
Private Sub SetLabelsColor(parent As Control, color As Color)
If (parent Is Nothing) OrElse (Not parent.HasChildren) Then Return
For Each ctl As Control In parent.Controls.OfType(Of Control)
If TypeOf ctl Is Label Then
ctl.BackColor = color
Else
If ctl.HasChildren Then
SetLabelsColor(ctl, color)
End If
End If
Next
End Sub
如果要修改面板内部而不是其他容器中的标签,可以修改触发递归的条件:
If (TypeOf ctl Is Panel) AndAlso (ctl.HasChildren) Then
SetLabelsColor(ctl, color)
End If
Jimi给出的答案对这个问题很有帮助。但是我想分享一个更一般的答案,它展示了如何使用扩展方法
获取所有子控件(子控件、子控件的子控件等)
可以创建扩展方法以列出控件的所有子代。编写此方法时,可以轻松利用迭代器函数和递归函数返回IEnumerable
: