从ListBoxItem获取ListBox对象

问题描述 投票:1回答:2

我正在研究DependencyProperty回调(PropertyChangedCallback),其中senderListBoxItem对象。我需要在代码中访问包含ListBoxListBoxItem

可能吗 ?

我试过listBoxItem.Parent,但它是null

c# .net wpf dependency-properties
2个回答
1
投票

试试这个:

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项。


5
投票

答案是:

VisualTreeHelper.GetParent(listBoxItem);

澄清:

VisualTreeHelper.GetParent(visualObject);

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

这意味着如果你想要给定ListBoxListBoxItem,因为ListboxItem的直接父代是ItemsPanel属性指定的Panel元素,你将不得不重复它,直到你得到ListBox

© www.soinside.com 2019 - 2024. All rights reserved.