首页 > 解决方案 > Get the name of the Parent of a child Panel

问题描述

I have a Panel object, which was dynamically created within another Panel object that was also dynamically created.
How can I get the name of the parent Panel from the child Panel?.

I only found information related to the Form object.

标签: vb.netwinformscontrolspanel

解决方案


有几种方法可能有助于找到孩子的父母。

Control 的直接父级由Control.Parent属性返回:

Dim parentName = [SomeControl].Parent.Name

Form 容器由FindForm()方法或Control.TopLevelControl属性返回:

Dim myForm1 = [SomeControl].FindForm()
Dim myForm2 = [SomeControl].TopLevelControl
Dim myFormName1 = myForm1.Name
Dim myFormName2 = myForm2.Name

您也可以使用GetContainerControl(),这将返回最外面的IContainerControl

UserControl 可以使用ParentForm属性(但它与 相同FindForm()

要查找不是表单的外部容器:

Private Function FindOuterContainer(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    While Not (TypeOf ctrl.Parent Is Form)
        ctrl = FindOuterContainer(ctrl.Parent)
    End While
    Return ctrl
End Function

Dim outerContainer = FindOuterContainer([SomeControl])
Dim outerContainerName = outerContainer.Name

要查找特定类型的外部祖先(例如,您在 TabControl 的 TabPage 内的 Panel 中有一个 Panel,并且您想知道 TabPage 是什么):

Private Function FindOuterContainerOfType(Of T)(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    While Not ((TypeOf ctrl.Parent Is Form) OrElse (TypeOf ctrl Is T))
        ctrl = FindOuterContainerOfType(Of T)(ctrl.Parent)
    End While
    Return ctrl
End Function

Dim parentTabPage = FindOuterContainerOfType(Of TabPage)([SomeControl])
Console.WriteLine(parentTabPage.Name)

要找到特定类型的最外层父级:(
例如,您在面板内的 TabControl 的 TabPage 内的面板内有一个面板,并且您希望获得最后一个面板)

Private Function FindOuterMostContainerOfType(Of T)(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    Dim outerParent As Control = Nothing
    While Not (TypeOf ctrl.Parent Is Form)
        If TypeOf ctrl.Parent Is T Then outerParent = ctrl.Parent
        ctrl = ctrl.Parent
    End While
    Return If(TypeOf outerParent Is T, outerParent, Nothing)
End Function


Dim outermostParentPanel = 
    TryCast(FindOuterMostContainerOfType(Of Panel)([SomeControl]), Panel)
Dim outermostParentPanelName = outermostParentPanel?.Name

[SomeControl]当然是想要找到其父母的子控件的实例。


推荐阅读