.net - 如何在表单及其嵌套面板中查找标签控件?

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

最佳答案

Jimi分享的答案非常适合这个问题。但我想分享一个更一般的答案,它展示了如何使用 Extension Methods , Iterator Functions , LINQEnumerable扩展方法。

获取所有后代控件(子项、子项的子项...)

您可以创建一个扩展方法来列出控件的所有后代。编写此方法时,您可以轻松利用迭代器函数和递归函数来返回 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

关于.net - 如何在表单及其嵌套面板中查找标签控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684650/

相关文章:

c# - .net 比 java 快

vb.net - 如何以编程方式向 VB.NET 中的窗体添加控件

winforms - 如何在高 DPI 上缩放 Windows 窗体按钮的图像?

c# - 如何将文本框中包含的数据传输到数据 GridView ?

c# - Winforms 中的可视 TreeMap

c# - 如何获取 .NET TrackBar 的跟踪器位置?

.net - 如何在执行 DataBind 之前对 DataSet 进行排序?

c# - 如何使 linq-to-sql 与抽象模型一起工作?

vb.net - 在 Winforms 中是否有等同于 trace=true 的东西?

c# - 如何从商店中干净地删除证书