【问题标题】:Get ListBox object from a ListBoxItem从 ListBoxItem 获取 ListBox 对象
【发布时间】:2019-02-09 12:50:43
【问题描述】:

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

有可能吗?

我试过listBoxItem.Parent 但它是null

【问题讨论】:

标签: c# .net wpf dependency-properties


【解决方案1】:

答案是:

VisualTreeHelper.GetParent(listBoxItem);

澄清一下:

VisualTreeHelper.GetParent(visualObject);

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

这意味着如果你想要给定ListBoxItemListBox,因为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&lt;ListBox&gt; 应该在可视化树中找到父项 ListBox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-03
      • 2012-04-13
      • 2018-07-09
      • 2022-01-11
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 2012-11-07
      相关资源
      最近更新 更多