带有值和文本的 ComboBoxItem

isp*_*iro 3 .net c# xaml windows-store-apps win-universal-app

我的目标是ComboBox让每个下拉项目都有一个特定的文本和一个与之关联的特定项目,例如,如果点击“blah” - 所选项目将为 3。

据我所知 - 只有一个“内容”同时代表文本和值。那么我如何分别获得两者?(在 XAML 或代码中,但没有 Binding。)

Meh*_*raz 6

强烈建议对 XAML 控件使用绑定,但是,您可以通过 Items 属性在 XAML 中定义 ComboBox 项:

  <ComboBox x:Name="comboBox1"
            SelectionChanged="ComboBox_SelectionChanged"
            SelectedValuePath="Tag">
     <ComboBox.Items>
        <ComboBoxItem Tag="1">Item 1</ComboBoxItem>
        <ComboBoxItem Tag="2">Item 2</ComboBoxItem>
        <ComboBoxItem Tag="3">Item 3</ComboBoxItem>
     </ComboBox.Items>
  </ComboBox>
Run Code Online (Sandbox Code Playgroud)

并在代码中获取所选项目:

 private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
     Debug.WriteLine(comboBox1.SelectedValue);
  }
Run Code Online (Sandbox Code Playgroud)

由于 ComboBox 项类没有 Value 属性,因此您可以使用 tag 属性来保存相应的值。设置 SelectedValuePath 属性告诉 ComboBox 将哪个属性用作值。