如何获取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;
}
看起来这个问题没有直接的解决方案..
答案 0 :(得分:4)
基本上,您想要检索特定类型的祖先。为此,我经常使用以下方法:
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>();
答案 1 :(得分:0)
与H.B. wrote也可以使用
var parent = ItemsControl.ItemsControlFromItemContainer(comboBoxItem) as ComboBox;