【发布时间】: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);
}
【问题讨论】: