按钮是TextBlock?

时间:2013-03-15 23:25:25

标签: silverlight silverlight-4.0 silverlight-5.0

我正在使用此功能通过ListBoxItem内的所有控件进行递归,Button内有TextBlockDataTemplate。它总是选择Button而不是TextBlock。任何人都可以看到我的功能有什么问题吗?

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

结束功能

1 个答案:

答案 0 :(得分: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

结束功能