如何找到 ComboBoxItem 的 ParentComboBox? [英] How to find the ParentComboBox of a ComboBoxItem?
本文介绍了如何找到 ComboBoxItem 的 ParentComboBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取 ComboBoxItem 的 ParentComboBox?
How can I get the ParentComboBox of an ComboBoxItem?
如果按下 Insert-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;
}
}
您可以按如下方式使用它:
You can use it as follows :
var parent = comboBoxItem.FindAncestor<ComboBox>();
这篇关于如何找到 ComboBoxItem 的 ParentComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文