1

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

2

2 Answers 2

6

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.

0
4

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.