1

如果我有一个带有未知数量标签的面板,我如何浏览所有标签并更改其中的 .text 值?我试过这样的事情:

for each x as label in mypanel
   x.text = "whatever"
next

但我收到一个错误,即 mypanel 不是集合。

标签是 mypanel 的子标签。

4

5 回答 5

2

对于获胜形式,请尝试:

for each x as Control in mypanel.Controls
   if TypeOf x Is Label Then
     CType(x, Label).text = "whatever"
   end if
next
于 2013-10-25T14:01:17.750 回答
0

取决于Panel这是什么类型的。 赢表格WPF ? 错误是对的,Panel不是集合。它只是一个对象。但它的一个属性可能是一个集合。

mypanel.Controls对于 WinForms 或mypanel.ChildrenWPF。如果层次结构多于直接子级,那么您可能需要进一步递归到该层次结构中。

于 2013-10-25T14:00:45.133 回答
0
For Each lbl As Label in myPanel.Controls
     lbl.Text = "whatever"
Next

这是假设 myPanel 上的所有内容都是标签。如果还有其他控件,则必须测试它们是否为标签:

For Each ctl as Control in myPanel.Controls
     If Ctl.GetType = Label.GetType Then
        CType(ctl, Label).text = "whatever"
     End if
Next
于 2013-10-25T14:01:57.070 回答
0

循环遍历面板中的所有控件,然后确定每个控件是否为Label,如下所示:

For Each theControl As Control In myPanel.Controls
    If TypeOf theControl Is Label Then
        ' Change the text here
        TryCast(theControl, Label).Text = "whatever"
    End If
Next

更新:

要考虑面板中的子控件,请执行以下操作:

Dim listOfLabels As New List(Of Control)

Public Sub GetAllLabelsIn(container As Control)
    For Each theControl As Control In container.Controls
        If TypeOf theControl Is Label Then    
            listOfLabels.Add(theControl)

            If theControl.Controls.Count > 0 Then
                GetAllLabelsIn(theControl)
            End If
        End If
    Next
End Sub

现在你可以这样称呼它:

listOfLabels = new List(Of Control)

GetAllLabelsIn(myPanel)

For Each theControl As Control In listOfLabels
    If TypeOf theControl Is Label Then
        ' Change the text here
        TryCast(theControl, Label).Text = "whatever"
    End If
Next
于 2013-10-25T14:05:47.787 回答
-1

您首先只能选择Labels。这也返回容器内容器内的标签等......

' Inside a module
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
    Dim result As New ArrayList()
    For Each ctrl As Control In parent.Controls
        If TypeOf ctrl Is T Then result.Add(ctrl)
        result.AddRange(ChildControls(Of T)(ctrl))
    Next
    Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function

用法:

For Each myLabel as Label in myPanel.ChildControls(Of Label)
    myLabel.Text = "I'm a label!"
Next
于 2013-10-25T14:23:32.370 回答