gpt4 book ai didi

c# - 如何找到 ComboBoxItem 的 ParentComboBox?

转载 作者:行者123 更新时间:2023-12-03 21:17:20 25 4
gpt4 key购买 nike

如何获取 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;
}

看起来这个问题没有直接的解决方案..

最佳答案

基本上,您想要检索特定类型的祖先。为此,我经常使用以下方法:

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

关于c# - 如何找到 ComboBoxItem 的 ParentComboBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2399967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com