我需要找到一個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);
}
太棒了!正是我需要的!謝謝H. – haagel 2011-04-27 09:07:18
用這種方法我可以殺死ComboBox野獸!非常感謝! – 2015-01-12 22:23:25