Мне нужно найти ComboBox, в котором находится ComboBoxItem.
В codebehind я улавливаю событие, когда нажимается ComboBoxItem, но я не знаю, какому из нескольких ComboBox принадлежит конкретный 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}" />
CodeBehind:
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);
}