获取WPF ComboBox的选定值

13

我该如何从下面的示例中获取所选值(例如Option1)作为string? 我已经尝试了许多谷歌上的建议,但无法获得字符串。

XAML:

<ComboBox x:Name="selectOption" Text="Select Option" 
                 SelectionChanged="selectOption_SelectionChanged" 
                 SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" >
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>

codebehind:


代码后端:
private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   var selectedValue = selectOption.SelectedValue; 
}

//elsewhere in code
var test = viewModel.VMselectedOption;

选定的值和测试都返回字符串 "System.Windows.Controls.ComboBoxItem: Option1" 而不是 "Option1"。

这应该非常简单,但我无法让它工作,也看不出哪里出了问题?


类似的问题在这里https://dev59.com/WnA65IYBdhLWcg3wnQBt 顶部的答案对我非常有效。 - SendETHToThisAddress
5个回答

21

你应该设置 SelectedValuePath="Content"。

<ComboBox x:Name="selectOption" Text="Select Option" 
                 SelectionChanged="selectOption_SelectionChanged" 
                 SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" 
                 SelectedValuePath="Content">
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>

这是最好、最简单的方法。谢谢。 - Gabriel

13

不应手动插入组合框项。使用ItemsSource设置它们。

基本上,您应该创建一个选项列表(或表示选项的对象),并将其设置为ItemsSource,这样您的SelectedItem将完全是所选的选项,而不是自动创建的包装ComboboxItem


2
你的回答是我在这里看到的唯一明智的答案。 - Federico Berasategui
@ooo:很高兴能帮到你。考虑到内容和表现的分离,使用“ItemsSource”是一个不错的选择。 - Vlad

8
string Value="";
if(myComboBox.SelectedIndex>=0) 
  Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString();

最好检查一下:if (((ComboBoxItem)myComboBox.SelectedItem).Content != null)。因为如果你对某个元素使用了IsSelected="True",那么在初始化后Content将会是null。 - Sasha

7

更新您的代码以获取comboboxItem的内容。

var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString();

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接