自动初始化控件

时间:2019-03-18 09:09:01

标签: vb.net winforms

我已经创建了一个需要初始化的自定义控件。实际上,我具有初始化我的自定义控件的功能(称为“ UserControl_Grille”):

 Private Sub Init_Grille()
    Me.grilleA.init_traduction(lignesTraduction)
    Me.grilleB.init_traduction(lignesTraduction)
    Me.grilleC.init_traduction(lignesTraduction)
    Me.grilleD.init_traduction(lignesTraduction)
    Me.grilleE.init_traduction(lignesTraduction)
    Me.grilleF.init_traduction(lignesTraduction)
    Me.grilleG.init_traduction(lignesTraduction)
    Me.grilleH.init_traduction(lignesTraduction)
End Sub

您可以看到它不是很值得,因为如果要添加新控件,则必须在此函数中添加它。

所以我尝试自动初始化,但是似乎它没有在我的表单中检测到任何自定义控件...:

Private Sub Init_Grille()
    For Each grille As UserControl_Grille In Me.Controls.OfType(Of UserControl_Grille)()
        grille.init_traduction(lignesTraduction)
    Next
End Sub

在调试模式下,它直接通过For Each循环。还有其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以递归滚动所有控件。

例如,此示例代码将返回您表单中所有标签的列表:

    Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' This list will hold all the labels that we find
        Dim results As List(Of Control) = New List(Of Control)

        ' Start searching for labels at the Form level 
        FindControls(Me, results)

        ' See how many labels we have found
        MessageBox.Show(results.Count)

    End Sub

    Private Sub FindControls(parent As Control, ByRef results As List(Of Control))
        For Each control As Control In parent.Controls

            If TypeOf control Is Label Then
                ' We found a label so we add it to the results
                results.Add(control)
            End If

            If Not control.Controls Is Nothing Then
                ' We loop through all sub-controls
                FindControls(control, results)
            End If
        Next
    End Sub
End Class

希望这会有所帮助:)