WPF 应用Visual tree递归查找通用类的控件

本文介绍了如何在WPF中使用Visual Tree递归查找父控件,特别是寻找具有特定名称的控件。提供了一个泛型函数示例,该函数能够在控件树中查找指定类型的依赖项对象,并在找到匹配的父控件时返回。文章还提到这种方法在处理模板和嵌套控件时非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近的一个项目用基类的Template来包装窗体,新建的窗体里的一个按钮需要调用程序里的另外一个窗体,显示时需要把这个窗体加到mainWindow里的DocumentContainer(syncfusion的类库)里去,但在template里却不能直接得到主窗口的DocumentContainer,试了很多方法例如template里传值但太过复杂,google了一下,终于在stack overflow网站里找到了答案,他是用visual tree查找child控件,而我是查找parent控件,思路都是一样。方程是用generic写的,也就是你可以得到任意类型的控件。

 

 

程序如下: 

 

 

    ''' <summary>

    ''' Finds a Child of a given item in the visual tree.

    ''' </summary>

    ''' <typeparam name="T">The type of the queried item.</typeparam>

    ''' <param name="root">A direct root of the queried item.</param>

    ''' <param name="parentName">name of parent control want to search</param>

    ''' <returns>The first parent item that matches the submitted type parameter.

    ''' If not matching item can be found, a null parent is being returned.</returns>

    ''' <remarks></remarks>

    ''' <writtenby name="" date="2011/02/05"></writtenby>

    Private Shared Function FindParent(Of T As DependencyObject)(ByVal root As DependencyObject, ByVal parentName As String) As DependencyObject

 

        Dim foundParent As T = Nothing

 

        If root Is Nothing Then

            Return foundParent

        Else

 

            Dim parent = VisualTreeHelper.GetParent(root)

            Dim frameworkElement As FrameworkElement = parent

 

            If frameworkElement IsNot Nothing AndAlso frameworkElement.Name = parentName Then

                foundParent = parent

 

            Else

                'recursively drill up the tree

                foundParent = FindParent(Of T)(parent, parentName)

            End If

        End If

 

        Return foundParent

 

    End Function

调用方法:

 

 

Dim objDependency As DependencyObject = CType(Me, DependencyObject)

 

 

Dim objDocumentContainer = FindParent(Of DependencyObject)(objDependency, "objDocumentContainer")

另外附图是visual tree的示意图,功能很强大,用的好的话帮助很大。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值