C# 如何找到ComboBoxItem的ParentComboBox?
如何获取ComboBoxItem的ParentComboBox 如果按Insert键,我想关闭打开的组合框:C# 如何找到ComboBoxItem的ParentComboBox?,c#,wpf,combobox,C#,Wpf,Combobox,如何获取ComboBoxItem的ParentComboBox 如果按Insert键,我想关闭打开的组合框: var focusedElement = Keyboard.FocusedElement; if (focusedElement is ComboBox) { var comboBox = focusedElement as ComboBox; comboBox.IsDropDownOpen = !comboBox.IsDropDownOpen; } els
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;
}
}
公共静态类DependencyObjectExtensions
{
公共静态T FindAncestor(此DependencyObject对象),其中T:DependencyObject
{
将对象FindAncestor(typeof(T))返回为T;
}
公共静态DependencyObject FindAncestor(此DependencyObject对象,类型为ancestorType)
{
var tmp=visualtreeheloper.GetParent(obj);
while(tmp!=null&&!ancestorType.IsAssignableFrom(tmp.GetType())
{
tmp=visualtreeheloper.GetParent(tmp);
}
返回tmp;
}
}
您可以按如下方式使用它:
var parent = comboBoxItem.FindAncestor<ComboBox>();
var parent=comboBoxItem.FindAncestor();
作为H.B.您也可以使用
var parent = ItemsControl.ItemsControlFromItemContainer(comboBoxItem) as ComboBox;
我认为用法应该如下:var parent=comboBoxItem.FindAncestor();这在一个无止境的while循环中结束:tmp始终是一个stackpanel不再有无止境的while循环:tmp=visualtreeheloper.GetParent(tmp)//而不是GetParent(obj)。。但是仍然是:null,没有ComboBox…Thomas的解决方案将我引向以下解决方案:var parent=comboBoxItem.FindAncestor()//不是组合框!var comboBox=parent.TemplatedParent作为comboBox;ComboBoxItem和ComboBox之间的链接可以使用ItemsPresenter创建。感谢您提供的解决方案。它还以相同的方式解决了ListBoxItem与其ListBox之间的连接。