从 ListBoxItem 获取 ListBox 对象

Get ListBox object from a ListBoxItem

我正在处理 DependencyProperty 回调 (PropertyChangedCallback),其中 sender 是一个 ListBoxItem 对象。我需要在代码中访问包含 ListBoxItemListBox

可能吗?

我试过了 listBoxItem.Parent 但它是 null

答案是:

VisualTreeHelper.GetParent(listBoxItem);

澄清一下:

VisualTreeHelper.GetParent(visualObject);

为您提供给定视觉对象的直接父级。

意思是如果你想要给定ListBoxItemListBox,因为ListboxItem的直接父级是ItemsPanel[=]指定的Panel元素26=],你将不得不重复它,直到你得到 ListBox

试试这个:

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> 应该在可视化树中找到父项 ListBox