如何在窗体及其嵌套面板中查找标签控件?

时间:2018-12-08 16:41:36

标签: .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

我的表单如下:

Form

2 个答案:

答案 0 :(得分:1)

您可以设置一个简单的递归方法来解析表单中的所有控件。

当集合中的控件的类型为Label时,请设置BackColor属性。
当控件包含其他控件时,解析其Controls集合以查看其是否包含一些标签;找到一个后,设置其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

如果要修改面板内部而不是其他容器内的标签,则可以修改触发递归的条件:

If (TypeOf ctl Is Panel) AndAlso (ctl.HasChildren) Then
    SetLabelsColor(ctl, color)
End If

答案 1 :(得分:1)

由吉米(Jimi)共享的答案对于这个问题非常有用。但我想分享一个更笼统的答案,该答案显示了如何使用Extension MethodsIterator FunctionsLINQEnumerable扩展方法。

获取所有后代控制(孩子,孩子的孩子,...)

您可以创建扩展方法以列出控件的所有后代。编写此方法时,您可以轻松利用Iterator函数和递归函数返回IEnumerable<Control>

Imports System.Runtime.CompilerServices
Module ControlExtensions

    <Extension()> 
    Public Iterator Function DescendantControls(c As Control) As IEnumerable(Of Control)
        For Each c1 As Control In c.Controls
            Yield c1
            For Each c2 As Control In c1.DescendantControls()
                Yield c2
            Next 
        Next
    End Function

End Module

然后,您可以使用扩展方法获取所有后代,并使用OfType来过滤特定类型的控件:

For Each c In Me.DescendantControls().OfType(Of Label)
    c.BackColor = Color.AliceBlue
Next