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

Sylvain B.
  • 719
  • 5
  • 31

2 Answers2

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.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
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.

mm8
  • 163,881
  • 10
  • 57
  • 88