获得ComboBox的价值

时间:2017-05-17 13:32:03

标签: c# wpf combobox

我得到以下ComboBox

<ComboBox Margin="5" SelectedValue="{Binding NewCourseWeekday, Mode=TwoWay}" Grid.Row="5" Grid.Column="1">
    <ComboBoxItem>Monday</ComboBoxItem>
    <ComboBoxItem>Tuesday</ComboBoxItem>
    <ComboBoxItem>Wednesday</ComboBoxItem>
    <ComboBoxItem>Thursday</ComboBoxItem>
    <ComboBoxItem>Friday</ComboBoxItem>
</ComboBox>

我有setter / getter:

public String NewCourseWeekday
{
    get { return _newCourseWeekday; }
    set
    {
        _newCourseWeekday = value;
        OnPropertyChanged();
    }
}

但是,如果我尝试使用此_newCourseWeekday,它并不仅仅包含工作日,但它包含System.Windows.Controls.ComboBoxItem: Monday之类的内容。我怎样才能选择字符串?

3 个答案:

答案 0 :(得分:2)

您应该将CascadeExpression个对象添加到string并将其ComboBox属性绑定到您的SelectedItem源属性:

NewCourseWeekday

<ComboBox Margin="5" SelectedItem="{Binding NewCourseWeekday, Mode=TwoWay}" Grid.Row="5" Grid.Column="1" xmlns:s="clr-namespace:System;assembly=mscorlib"> <s:String>Monday</s:String> <s:String>Tuesday</s:String> <s:String>Wednesday</s:String> <s:String>Thursday</s:String> <s:String>Friday</s:String> </ComboBox> 属性不能设置为string值。

答案 1 :(得分:1)

通过指定所选值是项目的实际内容而不是ComboBoxItem本身,您应该能够获得您期望的字符串。为此,请使用SelectedValuePath属性,并将其设置为Content

<ComboBox Margin="5" SelectedValuePath="Content" SelectedValue="{Binding NewCourseWeekday}" Grid.Row="5" Grid.Column="1">
    <ComboBoxItem>Monday</ComboBoxItem>
    <ComboBoxItem>Tuesday</ComboBoxItem>
    <ComboBoxItem>Wednesday</ComboBoxItem>
    <ComboBoxItem>Thursday</ComboBoxItem>
    <ComboBoxItem>Friday</ComboBoxItem>
</ComboBox>

答案 2 :(得分:-1)

你必须将NewCourseWeekday绑定到SelectedItem而不是绑定到SelectedValue