Reputation: 739
I am working on a DependencyProperty
callback (PropertyChangedCallback
) where the sender
is a ListBoxItem
object. I need in the code to access the ListBox
that is containing the ListBoxItem
.
Is it possible ?
I have tried listBoxItem.Parent
but it is null
Upvotes: 1
Views: 1448
Reputation: 5203
And the answer is:
VisualTreeHelper.GetParent(listBoxItem);
To clarify:
VisualTreeHelper.GetParent(visualObject);
Gives you the direct parent of the given visual object.
It means that if you want the ListBox
of the given ListBoxItem
, since the direct parent of ListboxItem
is the Panel element specified by the ItemsPanel
property, you will have to repeat it 'till you get the ListBox
.
Upvotes: 6
Reputation: 169240
Try this:
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
ListBoxItem lbi = sender as ListBoxItem;
ListBox lb = FindParent<ListBox>(lbi);
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
FindParent<ListBox>
should find the parent ListBox
item in the visual tree.
Upvotes: 4