【发布时间】:2020-06-05 13:25:34
【问题描述】:
我面临的问题与大多数人完全相反——我可以得到SelectedItem 的DataContext,但不能得到项目本身(ComboBoxItem):
private void TypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is ComboBox comboBox)
{
//always null, fetches UserType object instead (which is the DataContext )
ComboBoxItem selectedComboBoxItem = comboBox.SelectedItem as ComboBoxItem;
}
}
我也尝试过访问ItemContainerGenerator,但它也总是返回null:
private void TypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.IsDropDownOpen = true; //attempt to force item generation
comboBox.IsDropDownOpen = false;
comboBox.UpdateLayout();
comboBox.ApplyTemplate();
//also always null no matter what
var item = comboBox.ItemContainerGenerator.ContainerFromItem(comboBox.SelectedItem);
}
}
如何获取当前选中的ComboBoxItem?
【问题讨论】:
-
如果您指的是项目名称,请尝试
comboBox.SelectedItem.ToString() -
是什么让您认为
SelectedItem是ComboBoxItem?ComboBox的ItemsSource是什么?comboBox.SelectedItem返回什么? -
@mm8 不是
ComboBoxItem我想强调一个与平时相反的问题:有DataContext,想要FrameworkElement。 ItemsSource 是UserType的列表。我需要访问ComboBoxItem的视觉属性之一。 -
在打开下拉菜单之前没有可视容器。你什么时候需要它,为什么?
-
ComboBox关闭时没有容器。