【问题标题】:Get ListBox object from a ListBoxItem从 ListBoxItem 获取 ListBox 对象
【发布时间】:2019-02-09 12:50:43
【问题描述】:
我正在处理 DependencyProperty 回调 (PropertyChangedCallback),其中 sender 是 ListBoxItem 对象。我需要在代码中访问包含ListBoxItem 的ListBox。
有可能吗?
我试过listBoxItem.Parent 但它是null
【问题讨论】:
标签:
c#
.net
wpf
dependency-properties
【解决方案1】:
答案是:
VisualTreeHelper.GetParent(listBoxItem);
澄清一下:
VisualTreeHelper.GetParent(visualObject);
为您提供给定视觉对象的直接父级。
这意味着如果你想要给定ListBoxItem 的ListBox,因为ListboxItem 的直接父元素是ItemsPanel 属性指定的Panel 元素,你将不得不重复它直到你得到ListBox。
【解决方案2】:
试试这个:
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。