vb.net - 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.
解决方案
有几种方法可能有助于找到孩子的父母。
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]
当然是想要找到其父母的子控件的实例。
推荐阅读
- office-addins - 如何将使用 Yo Office 创建的 Outlook 加载项部署到我们自己的 ubuntu 服务器?
- python - How do you apply layer normalization in an RNN using tf.keras?
- javascript - Add various colors to groups in Vega radial chart
- sql - 从行窗口中获取最大值作为所有行的新列
- javascript - 如何在谷歌的操作中禁用列表中的项目选择?
- reactjs - React SVG不会在属性更新时重新渲染
- python - 每次访问时更改的模拟属性
- c++ - 如何使用字符串将无效操作数修复为二进制表达式?
- perl - 来自 CSV 文件的 Undef 值会产生不良结果
- android - 当我想用 epson TM T20 打印我的票时,我可以打印我的票,但异常状态 err_illegal 到 affich