简体   繁体   English

获取wpf组合框选择的值

[英]Get wpf combobox selected value

How do I get the selected value (eg Option1 ) as a string from my example below. 如何从下面的示例中将所选值(例如Option1 )作为string获取。 I've tried loads of suggestions on Google but can't get the string. 我在Google上尝试过大量的建议,但无法获得字符串。

XAML: 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;

Both selectedValue and test return the string " System.Windows.Controls.ComboBoxItem: Option1 " and not " Option1 " selectedValue和test都返回字符串“ System.Windows.Controls.ComboBoxItem:Option1 ”而不是“ Option1

This should be really simple but I just cannot get this working or see what is wrong? 这应该是非常简单但我不能让这个工作或看到什么是错的?

You should set SelectedValuePath="Content". 您应该设置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>

You shouldn't insert the combobox items manually. 您不应手动插入组合框项目。 Set them by using ItemsSource . 使用ItemsSource设置它们。

Basically you should create a list of options (or objects representing options) and set them as ItemsSource , this way your SelectedItem will be exactly the option which is selected, not the automatically created wrapping ComboboxItem . 基本上你应该创建一个选项列表(或表示选项的对象)并将它们设置为ItemsSource ,这样你的SelectedItem就是选择的选项,而不是自动创建的包装ComboboxItem

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

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

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

ComboBoxItem.Content的类型为Object,因此您需要自己转换项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM