How to find the ParentComboBox of a ComboBoxItem?

前端 未结 2 415
悲&欢浪女
悲&欢浪女 2021-01-20 02:09

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          


        
2条回答
  •  温柔的废话
    2021-01-20 02:36

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

提交回复
热议问题