tags:

views:

127

answers:

1

How can I get the ParentComboBox of an ComboBoxItem?

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..

+1  A: 

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

}

You can use it as follows :

var parent = comboBoxItem.FindAncestor<ComboBox>();
Thomas Levesque
I think the usage should be as follow: var parent = comboBoxItem.FindAncestor<ComboBox>();This ends in an endless while-loop: tmp is always a StackPanel
WaltiD
No endless while-loop anymore:tmp = VisualTreeHelper.GetParent(tmp); //Instead of GetParent(obj)..But still: null, no ComboBox...
WaltiD
oops... you're right in both cases ;). I fixed the code
Thomas Levesque