我使用这个函数来递归遍历ListBoxItem中的所有控件,并且在DataTemplate中既有Button又有TextBlock。它总是选择按钮而不是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 resultEnd函数
发布于 2013-03-16 07:52:09
看起来很简单,但它确实有效!不能解释为什么它会与这条线下面的类型混淆。
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 resultEnd函数
https://stackoverflow.com/questions/15443668
复制相似问题