获取WPF组合框选择的值 [英] Get wpf combobox selected value

查看:134
本文介绍了获取WPF组合框选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得所选择的值(如选项1 )为字符串从下面我的例子。 。我试过的建议负荷在谷歌,但不能得到字符串

How do I get the selected value (eg Option1) as a string from my example below. I've tried loads of suggestions on Google but can't get the 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>



代码隐藏:

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

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

This should be really simple but I just cannot get this working or see what is wrong?

推荐答案

您不应手动插入组合框项目。通过使用 的ItemsSource

You shouldn't insert the combobox items manually. Set them by using ItemsSource.

基本上你应该创建的选项(或代表选择对象)列表,并将其设置为的ItemsSource ,这样一来你的的SelectedItem 将是到底哪个选择了该选项,而不是自动创建的包装 ComboboxItem

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.

这篇关于获取WPF组合框选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆