0

我正在使用此函数通过 a 内的所有控件进行递归,并且ListBoxItem我在. 它总是选择 Button 而不是. 谁能看到我的功能有什么问题?ButtonTextBlockDataTemplateTextBlock

Private Function FindVisualChild(ByVal obj As DependencyObject) As TextBlock
 Dim result As TextBlock = Nothing
 For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
  Dim child As DependencyObject = TryCast(VisualTreeHelper.GetChild(obj, i), DependencyObject)
  If Not child Is Nothing AndAlso TypeOf child Is DependencyObject Then
    If TypeOf child Is TextBlock Then
      Dim tbl As TextBlock = TryCast(child, TextBlock)
      If Not tbl Is Nothing Then result = tbl
    Else
      Dim tbl As TextBlock = FindVisualChild(child)
      If Not tbl Is Nothing Then result = tbl : Exit For
    End If
  End If
Next
Return result

结束功能

4

1 回答 1

0

看似简单,但确实有效!没有解释为什么它与此行下方的类型混淆

Private Function FindVisualChild(ByVal obj As DependencyObject) As TextBlock
Dim result As TextBlock = Nothing
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
  Dim child As DependencyObject = TryCast(VisualTreeHelper.GetChild(obj, i), DependencyObject)
  If TypeOf child Is Button Then Continue For 'fixes it
  If Not child Is Nothing AndAlso TypeOf child Is DependencyObject Then
    If TypeOf child Is TextBlock Then
      Dim tbl As TextBlock = TryCast(child, TextBlock)
      If Not tbl Is Nothing Then result = tbl
    Else
      Dim tbl As TextBlock = FindVisualChild(child)
      If Not tbl Is Nothing Then result = tbl : Exit For
    End If
  End If
Next
Return result

结束功能

于 2013-03-15T23:52:09.423 回答