2013-10-18 104 views
11

我如何从下面的示例中获取选定值(例如Option1)作为string。我在Google上尝试了大量建议,但无法获取字符串。获取wpf组合框选定的值

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> 

代码隐藏:

private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var selectedValue = selectOption.SelectedValue; 
} 

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

两个了selectedValue和测试返回字符串 “System.Windows.Controls.ComboBoxItem:选项”,而不是“选项1

这应该很简单,但我不能得到这个工作或看看有什么不对?

回答

12

您不应手动插入组合框项目。使用ItemsSource进行设置。

基本上你应该创建的选项(或代表选择的对象)的列表,并将它们设置为ItemsSource,这样一来你的SelectedItem将完全被选择的选项,而不是自动创建包装ComboboxItem

+2

你是我见过的唯一明智的答案。 –

+0

它使用ItemsSource完美工作,谢谢。 – user3357963

+0

@ooo:很高兴它有帮助。考虑到内容和演示的分离,使用'ItemsSource'是一个不错的选择。 – Vlad

7

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

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

最好检查:if(((ComboBoxItem)myComboBox.SelectedItem).Content!= null)。因为如果对某些元素使用IsSelected =“True”,则初始化后内容将为空。 – Sasha

18

您应该设置SelectedValuePath = “内容”。

<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>