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

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

问题描述

我需要更改窗体和嵌套面板中所有Label的背景颜色。

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 属性。

当控件包含其他控件时,解析其 Contro ls 集合以查看它是否包含一些标签;找到一个后,设置其 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天全站免登陆