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

    技术2024-10-19  22

    最近的一个项目用基类的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的示意图,功能很强大,用的好的话帮助很大。

    最新回复(0)