How to retrieve parent ListBoxItem container? In the following example, I can go to ListBoxItem, higher than 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 empty):

source share