2011-04-27 48 views
4

我需要找到一個ComboBoxItem駐留在ComboBox組合框。獲取一個ComboBoxItem駐留在

在代碼隱藏我趕上點擊一個ComboBoxItem當一個事件,但我不知道有幾家組合框的哪一個該特定的ComboBoxItem屬於。我如何找到組合框?

通常情況下,您可以使用LogicalTreeHelper.GetParent()並遍歷ComboBoxItem中的邏輯樹來查找組合框。但是,這僅適用於ComboBoxItems手動添加到組合框,而不是通過數據綁定將項應用於ComboBox的情況。當使用數據綁定時,ComboBoxItems沒有將ComboBox作爲邏輯父項(我不明白爲什麼)。

任何想法?

更多信息:

下面是一些代碼重構我的問題(不是我的實際代碼)。如果我將數據綁定ComboBoxItems更改爲手動設置(在XAML中),則變量「comboBox」將設置爲正確的ComboBox。現在comboBox只有null。

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

回答

16

這可能是你在找什麼:

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

我愛怎麼描述這個方法名是。


在一個側面說明,有可以在其中讓你與模板數據,反之亦然機構的容器的屬性ItemsControl.ItemContainerGenerator可以找到一些有用的方法。

另一方面,請注意,您通常應該使用而不是正在使用它們中的任何一種,而是實際使用數據綁定。

+0

太棒了!正是我需要的!謝謝H. – haagel 2011-04-27 09:07:18

+0

用這種方法我可以殺死ComboBox野獸!非常感謝! – 2015-01-12 22:23:25