【问题标题】:Get the ComboBox that a ComboBoxItem resides in获取 ComboBoxItem 所在的 ComboBox
【发布时间】:2011-08-13 15:19:13
【问题描述】:

我需要找到 ComboBoxItem 所在的 ComboBox。

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

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

有什么想法吗?

更多信息:

下面是一些重构我的问题的代码(不是我的实际代码)。如果我将从数据绑定 ComboBoxItems 更改为手动设置它们(在 XAML 中),则变量“comboBox”将设置为正确的 ComboBox。现在 comboBox 只是空的。

XAML:

<ComboBox Name="MyComboBox" ItemsSource="{Binding Path=ComboBoxItems, Mode=OneTime}" />

代码隐藏:

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

【问题讨论】:

    标签: wpf combobox


    【解决方案1】:

    这可能就是你要找的东西:

    var comboBox = ItemsControl.ItemsControlFromItemContainer(comboBoxItem) as ComboBox;
    

    我喜欢这个方法名称的描述性。


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

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

    【讨论】:

    • 太棒了!正是我需要的!谢谢 H.B.
    • 用这个方法我可以杀死 ComboBox 野兽!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多