如何在表单及其嵌套面板中找到标签控件? [英] How to find Label Controls inside a Form and its nested Panels?

查看:40
本文介绍了如何在表单及其嵌套面板中找到标签控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改表单和嵌套面板中所有标签的背景颜色.

I need to change the background color of all the Labels inside a Form and nested Panels.

我试过这段代码,但它只改变了表单内标签的颜色,而不是面板内所有标签的颜色.

I tried this code but it only changes the color of the Labels that are inside the Form, not all the Labels inside the Panels.

  For Each Label As Control In Me.Controls
      If Label.GetType.ToString = "System.Windows.Forms.panel" Then
          Label.BackColor = Color.AliceBlue
      End If
  Next

我的表单如下所示:

推荐答案

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

You could setup a simple recursive method that parses all Controls in a Form.

当集合中的控件类型为 Label 时,设置 BackColor 属性.
当Control包含其他Control时,解析其Controls集合,看是否包含一些Label;找到后,设置其BackColor.

When a Control in the collection is of type Label, set the BackColor property.
When the Control contains other Controls, parse its Controls collection to see whether it contains some Labels; when one is found, set its 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 you want to modify the Labels that are inside Panels and not other containers, you could modify the condition that triggers the recursion:

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

这篇关于如何在表单及其嵌套面板中找到标签控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆