我需要更改表单和嵌套面板内所有标签的背景颜色。
我尝试了这段代码,但它只更改了表单内标签的颜色,而不是面板内所有标签的颜色。
For Each Label As Control In Me.Controls
If Label.GetType.ToString = "System.Windows.Forms.panel" Then
Label.BackColor = Color.AliceBlue
End If
Next
我的表单如下所示:
最佳答案
Jimi分享的答案非常适合这个问题。但我想分享一个更一般的答案,它展示了如何使用 Extension Methods , Iterator Functions , LINQ和 Enumerable扩展方法。
获取所有后代控件(子项、子项的子项...)
您可以创建一个扩展方法来列出控件的所有后代。编写此方法时,您可以轻松利用迭代器函数和递归函数来返回 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/