簡體   English   中英

如何遍歷容器中的所有對象?

[英]How do I iterate through all the objects in a container?

如果我的面板中的標簽數量未知,如何瀏覽所有標簽並更改其中的.text值? 我嘗試過這樣的事情:

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

但是我得到一個錯誤,那就是mypanel不是集合。

標簽是mypanel的子級。

對於贏獎形式,請嘗試:

for each x as Control in mypanel.Controls
   if TypeOf x Is Label Then
     CType(x, Label).text = "whatever"
   end if
next

取決於這是哪種Panel WinForms的 WPF 錯誤是正確的, Panel不是集合。 這只是一個對象。 但是它的特性之一可能是集合。

mypanel.Controls為的WinForms,或mypanel.Children為WPF。 如果層次結構比直接子級多,那么您可能需要進一步遞歸到該層次結構中。

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

遍歷面板中的所有控件,然后確定每個控件是否為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

首先,您只能選擇Label 這還會在容器等內部的容器內返回標簽...

' 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM