【发布时间】:2010-04-13 20:53:02
【问题描述】:
如何提取 ListBoxItem 的父容器? 在下面的示例中,我可以一直到 ListBoxItem,比我得到的更高:
<ListBox Name="lbAddress">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Click="Button_Click"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Private Sub Button_Click(sender As Button, e As RoutedEventArgs)
Dim lbAddress = GetAncestor(Of ListBox) 'Result: Nothing
End Sub
Public Shared Function GetAncestor(Of T)(reference As DependencyObject) As T
Dim parent = GetParent(reference)
While parent IsNot Nothing AndAlso Not parent.GetType.Equals(GetType(T))
parent = GetAncestor(Of T)(parent)
End While
If parent IsNot Nothing Then _
Return If(parent.GetType Is GetType(T), parent, Nothing)
Return Nothing
End Sub
Public Function GetParent(reference As DependencyObject) As DependencyObject
Dim parent As DependencyObject = Nothing
If TypeOf reference Is FrameworkElement Then
parent = DirectCast(reference, FrameworkElement).Parent
ElseIf TypeOf reference Is FrameworkContentElement Then
parent = DirectCast(reference, FrameworkContentElement).Parent
End If
Return If(parent, VisualTreeHelper.GetParent(reference))
End Function
更新
会发生这种情况(注意“父”变量保持为空):
【问题讨论】:
-
请注意,我希望方向是这种方式,而不是从顶部项目中搜索名称“lbAddress”。
-
GetVisualAncestor/GetAncestor 是扩展方法吗?
-
是的,不过和上面的sn-p一样。
标签: wpf xaml listbox listboxitem visual-tree