ListBoxItem.Parent returns nothing, unable to get it thru VisualTreeHelper.GetParent either
Posted
by Shimmy
on Stack Overflow
See other posts from Stack Overflow
or by Shimmy
Published on 2010-04-13T20:53:02Z
Indexed on
2010/04/15
3:43 UTC
Read the original article
Hit count: 545
How do I extract the parent container of a ListBoxItem? In the following example I can go till the ListBoxItem, higher than that I get Nothing:
<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
Update
This is what happens (note that the 'parent' variable remains null):
© Stack Overflow or respective owner