如何获取 ComboBoxItem 的 ParentComboBox?

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

 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;
 }

看起来这个问题没有直接的解决方案..

最佳答案

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

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>();

关于c# - 如何找到 ComboBoxItem 的 ParentComboBox?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2399967/

10-12 15:21