WPF组合框获取所选项目的文本和内部值(未显示),以下面我有WPF组合框组合框

问题描述:

的每个项目相关联:WPF组合框获取所选项目的文本和内部值(未显示),以下面我有WPF组合框组合框

<ComboBox x:Name="MyComboBox" 
      Grid.Column="1" 
      SelectionChanged="MyComboBox_SelectionChanged"> 
    <ComboBox.ItemsPanel> 
     <ItemsPanelTemplate> 
      <VirtualizingStackPanel /> 
     </ItemsPanelTemplate> 
    </ComboBox.ItemsPanel> 

    <ComboBoxItem Name="cbiEmployeeManagerType"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="/Resources/Manager.png" /> 
      <TextBlock Foreground="AliceBlue" 
         VerticalAlignment="Center">Manager</TextBlock> 
     </StackPanel> 
    </ComboBoxItem> 
    <ComboBoxItem Name="cbiEmployeeEngineerType"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="/Resources/Engineer.png" /> 
      <TextBlock Foreground="AliceBlue" 
         VerticalAlignment="Center">Engineer</TextBlock> 
     </StackPanel> 
    </ComboBoxItem> 
</ComboBox> 

第一个问题

MyComboBox_SelectionChanged我知道如何通过MyComboBox.SelectedIndex来检测当前在组合框中选择哪个项目,但我不知道如何获取显示并且当前在组合框中选择的文本。例如,如果我选择了我的组合框中的第二个项目,我想获得“工程师”。我该怎么做?

问题二

此外,我愿做一样的组合框的WinForms,可以在其中显示的成员(在WinForms的组合框的DisplayMember属性),并在内部给它的成员值相关联(ValueMember winform中的组合框的属性),当你选择组合框内的项目时,你可以阅读它。例如,假设以下combox项目及其相关值。

  • “经理人”:1000A
  • “工程师”:1000B

因此,“经理”和“工程师”会被显示在COMBOX时,我会选择“经理人”我会得到其相关的值,即1000A,对于工程师也是如此。在WPF中可能吗?如果是这样如何?我已经读过,可以使用DisplayMemberPathSelectedValuePath组合框属性,但我不知道该怎么做。我是否需要创建一个类并从那里填充组合,然后使用绑定?任何代码将高度赞赏。

UPDATE: 对于第二个问题,最后我做了类似于解释herehere

+0

有两点需要注意。 1.在ComboBox中使用VirtualizingStackPanel似乎没有任何意义。删除整个ComboBox.ItemsPanel。 2.重复添加带有两个子元素的StackPanel的ComboBoxItems。这应该通过ComboBox的ItemTemplate属性中的DataTemplate完成。在DataTemplate中,您将绑定到项目类型的属性。 ComboBox的ItemsSource属性将绑定到此项类型的集合。有关如何启动,请参见[数据模板概述](https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/data/data-templating-overview)。 – Clemens

对于您可以通过SelectionChanged事件的SelectionChangedEventArgs e用这种代码行的挖掘访问ComboBoxItem的TextBlock中的第一个问题:

private void MyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var selectedItem = e.AddedItems[0] as ComboBoxItem; 
    var itemStackPanel = selectedItem.Contents as StackPanel; 

    // Get the TextBlock object from 'itemStackPanel' object 
    // TextBlock is with index 1 because it is defined second 
    // after Image inside the StackPanel in your XAML 
    var textBlock = itemStackPanel.Children[1] as TextBlock; 
    // This variable will hold 'Engineer' or 'Manager' 
    var selectedText = textBlock.Text; 

} 

,或者您可以使用结合了所有该短行上面一行代码: (该?.是C#6功能,以防东西,检查空不顺心)

var selectedText = (((e.AddedItems[0] as ComboBoxItem)?.Content as StackPanel)?.Children[1] as TextBlock)?.Text;