【问题标题】:WPF get selected ComboBoxItemWPF 获取选中的 ComboBoxItem
【发布时间】:2020-06-05 13:25:34
【问题描述】:

我面临的问题与大多数人完全相反——我可以得到SelectedItemDataContext,但不能得到项目本身(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()
  • 是什么让您认为SelectedItemComboBoxItemComboBoxItemsSource 是什么? comboBox.SelectedItem 返回什么?
  • @mm8 不是ComboBoxItem 我想强调一个与平时相反的问题:有DataContext,想要FrameworkElement。 ItemsSource 是UserType 的列表。我需要访问ComboBoxItem 的视觉属性之一。
  • 在打开下拉菜单之前没有可视容器。你什么时候需要它,为什么?
  • ComboBox关闭时没有容器。

标签: c# wpf xaml combobox


【解决方案1】:

似乎UpdateLayout()/comboBox.ApplyTemplate() 确保ItemContainerGenerator 方法仅在comboBox.IsDropDownOpen 当前为true 时才有效:

private void TypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   if (sender is ComboBox comboBox)
   {
      comboBox.IsDropDownOpen = true;
      comboBox.UpdateLayout();
      comboBox.ApplyTemplate();
      var item = comboBox.ItemContainerGenerator.ContainerFromItem(comboBox.SelectedItem);
      comboBox.IsDropDownOpen = false;
      //close after geting item ^^^^^
   }
}

这与我在组合框项目ItemContainerGenerator 上的original source 相矛盾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多