VB中的WPF:如何从String中获取表单中的textBox?

时间:2015-05-24 08:22:24

标签: wpf vb.net xaml

我正在尝试从String中获取对象TextBox,其中String等于TextBox.Name

我的XAML看起来像这样:

<Window>
<DockPanel>
<TabItem Header="3">
<Grid>
   <TextBox x:Name="textBox1"/>
   <TextBox x:Name="textBox2"/>
</Grid>
</TabItem>
</Dockpanel>
</Window>

在VB中,我使这个功能无法正常工作

Private Function getTextboxOutName(ByVal parent As DependencyObject, ByVal textBoxName As String) As Object
    Dim element As Object

    Dim aantalElementen As Integer = VisualTreeHelper.GetChildrenCount(parent)
    If aantalElementen > 0 Then
        For n As Integer = 0 To aantalElementen - 1
            Dim child As DependencyObject = VisualTreeHelper.GetChild(parent, n)
            element = child
            If element.Name = textBoxName Then
                Return element
            End If
        Next
    End If

    Return Nothing
End Function

我做错了什么?

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以使用您提供的名称访问后面代码中的元素。

或者如果您仍想枚举树,则应使用递归方法来查找元素。 msdn显示了以下示例msdn VisualTreeHelper.GetChildCount

     Public Shared Sub EnumVisual(ByVal myVisual As Visual)
        For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(myVisual) - 1
            ' Retrieve child visual at specified index value.
            Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(myVisual, i), Visual)

            ' Do processing of the child visual object.

            ' Enumerate children of the child visual object.
            EnumVisual(childVisual)
        Next i
    End Sub