获取ComboBoxItem所在的ComboBox

haa*_*gel 4 wpf combobox

我需要找到ComboBoxItem所在的ComboBox.

在代码隐藏中,我在单击ComboBoxItem时捕获一个事件,但我不知道特定ComboBoxItem所属的几个ComboBox中的哪一个.我如何找到ComboBox?

通常,您可以使用LogicalTreeHelper.GetParent()并遍历ComboBoxItem中的逻辑树以查找ComboBox.但这仅在ComboBoxItems手动添加到ComboBox时才有效,而不是在将项目应用于带有数据绑定的ComboBox时.使用数据绑定时,ComboBoxItems没有将ComboBox作为逻辑父项(我不明白为什么).

有任何想法吗?

更多信息:

下面是一些代码重建我的问题(不是我的实际代码).如果我将数据绑定ComboBoxItems更改为手动设置(在XAML中),变量"comboBox"将被设置为正确的ComboBox.现在comboBox只是null.

XAML:

<ComboBox Name="MyComboBox" ItemsSource="{Binding Path=ComboBoxItems, Mode=OneTime}" />
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

public MainWindow()
{
    InitializeComponent();

    MyComboBox.DataContext = this;
    this.PreviewMouseDown += MainWindow_MouseDown;
}

public BindingList<string> ComboBoxItems
{
    get
    {
        BindingList<string> items = new BindingList<string>();
        items.Add("Item E");
        items.Add("Item F");
        items.Add("Item G");
        items.Add("Item H");
        return items;
    }
}

private void MainWindow_MouseDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject clickedObject = e.OriginalSource as DependencyObject;
    ComboBoxItem comboBoxItem = FindVisualParent<ComboBoxItem>(clickedObject);
    if (comboBoxItem != null)
    {
        ComboBox comboBox = FindLogicalParent<ComboBox>(comboBoxItem);
    }
}

//Tries to find visual parent of the specified type.
private static T FindVisualParent<T>(DependencyObject childElement) where T : DependencyObject
{
    DependencyObject parent = VisualTreeHelper.GetParent(childElement);
    T parentAsT = parent as T;
    if (parent == null)
    {
        return null;
    }
    else if (parentAsT != null)
    {
        return parentAsT;
    }
    return FindVisualParent<T>(parent);
}

//Tries to find logical parent of the specified type.
private static T FindLogicalParent<T>(DependencyObject childElement) where T : DependencyObject
{
    DependencyObject parent = LogicalTreeHelper.GetParent(childElement);
    T parentAsT = parent as T;
    if (parent == null)
    {
        return null;
    }
    else if(parentAsT != null)
    {
        return parentAsT;
    }
    return FindLogicalParent<T>(parent);
}
Run Code Online (Sandbox Code Playgroud)

H.B*_*.B. 19

这可能是你正在寻找的:

var comboBox = ItemsControl.ItemsControlFromItemContainer(comboBoxItem) as ComboBox;
Run Code Online (Sandbox Code Playgroud)

我喜欢方法名称的描述性.


另外,还有一些其他有用的方法可以在属性ItemsControl.ItemContainerGenerator中找到,它可以让您获得与模板化数据相关联的容器,反之亦然.

另一方面,您通常应该使用其中任何一个,而是实际使用数据绑定.