本文介绍了如何查找ComboBoxItem的ParentComboBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取ComboBoxItem的ParentComboBox?

How can I get the ParentComboBox of an ComboBoxItem?

如果按下了插入 -Key,我想关闭一个打开的ComboBox :

I would like to close an open ComboBox if the Insert-Key is pressed:

 var focusedElement = Keyboard.FocusedElement;
 if (focusedElement is ComboBox)
 {
     var comboBox = focusedElement as ComboBox;
     comboBox.IsDropDownOpen = !comboBox.IsDropDownOpen;
 }
 else if (focusedElement is ComboBoxItem)
 {
     var comboBoxItem = focusedElement as ComboBoxItem;
     var parent = comboBoxItem.Parent; //this is null
     var parent = comboBoxItem.ParentComboBox; //ParentComboBox is private
     parent.IsDropDownOpen = !parent.IsDropDownOpen;
 }

看起来没有直接的解决方案。

It looks like there's no straight forward solution for this problem..

推荐答案

基本上,您要检索特定类型的祖先。为此,我经常使用以下方法:

Basically, you want to retrieve an ancestor of a specific type. To do that, I often use the following method :

public static class DependencyObjectExtensions
{

    public static T FindAncestor<T>(this DependencyObject obj) where T : DependencyObject
    {
        return obj.FindAncestor(typeof(T)) as T;
    }

    public static DependencyObject FindAncestor(this DependencyObject obj, Type ancestorType)
    {
        var tmp = VisualTreeHelper.GetParent(obj);
        while (tmp != null && !ancestorType.IsAssignableFrom(tmp.GetType()))
        {
            tmp = VisualTreeHelper.GetParent(tmp);
        }
        return tmp;
    }

}
var parent = comboBoxItem.FindAncestor<ComboBox>();

这篇关于如何查找ComboBoxItem的ParentComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:49