在运行时将控件添加到用户控件的内部面板

Add control at runtime to user control's inner panel

我有一个包含 2 个面板的用户控件。 Panel1 是 Panel2 的父级,因此 Panel2 位于 Panel1 容器内。现在,在运行时,我想将控件添加到我的用户控件中。这些新控件必须放在 Panel2 中。使用 myUserControl.Controls.Add 添加控件通常会将新控件放入用户控件本身,而不是在 Panel2 中。我希望 Panel2 成为在运行时添加到用户控件的所有控件的默认容器。如何做到这一点?

可以覆盖OnControlAdded,验证UC句柄是否已经创建(InitiaizeComponent()已经被执行,所以在Designer中添加的所有子控件都已经添加到UC的控件集合中),然后将新控件添加到 Panel2.Controls 集合:

Public Class MyUSerControl
    Inherits UserControl

    Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
        If IsHandleCreated AndAlso e.Control IsNot Panel1 Then
            Panel2.Controls.Add(e.Control)
        End If
        MyBase.OnControlAdded(e)
    End Sub
End Class

或者,您可以添加一个 public 方法来执行此操作:

Dim btn1 = New Button() With {.Text = "Button1", .Name = "Button1"}
Dim btn2 = New Button() With {.Text = "Button2", .Name = "Button2"}

myUSerControl.AddControls(btn1)
' Or
myUSerControl.AddControls({btn1, btn2})

Public Class MyUSerControl
    Inherits UserControl

    Public Sub AddControls(ParamArray newControls As Control())
        Panel2.Controls.AddRange(newControls)
    End Sub
End Class