wpf组合框中奇怪的数据绑定问题

the*_*age 2 wpf combobox mvvm mvvm-light

我正在编写WPF中的简单GUI.目前我在ComboBox中有一个静态列表,如下所示:

    <ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
        SelectedItem="{Binding fruit, Mode=TwoWay}">
        <ComboBoxItem>apple</ComboBoxItem>
        <ComboBoxItem>orange</ComboBoxItem>
        <ComboBoxItem>grape</ComboBoxItem>
        <ComboBoxItem>banana</ComboBoxItem>
    </ComboBox>
Run Code Online (Sandbox Code Playgroud)

我将SelectedItem绑定到我的代码中的单例,该代码已经初始化并在别处使用.

我穿上了断点getfruit,它返回"葡萄",但所选择的项目始终是空白.我甚至添加了一个按钮,以便我可以手动调用RaisePropertyChanged,但是RaisePropertyChange调用也没有做任何事情.

最后,MVVMLight提供了可混合性.对于没有重要的原因我改变了从ComboBox绑定SelectedItemText 只要我做了,我的设计时间填写表格与预期值,但是,该代码运行时,将盒子继续坐在空状态

Pav*_*kov 5

这是因为你有型的项目ComboBoxItemComboBox,但您要绑定到属性的类型的string.

你有三个选择:

1.而不是添加ComboBoxItem项目添加String项目:

<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
    SelectedItem="{Binding fruit, Mode=TwoWay}">
    <sys:String>apple</sys:String>
    <sys:String>orange</sys:String>
    <sys:String>grape</sys:String>
    <sys:String>banana</sys:String>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

2.而不是SelectedItem绑定SelectedValue并指定SelectedValuePathContent:

<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
    SelectedValue="{Binding fruit, Mode=TwoWay}"
    SelectedValuePath="Content">
    <ComboBoxItem>apple</ComboBoxItem>
    <ComboBoxItem>orange</ComboBoxItem>
    <ComboBoxItem>grape</ComboBoxItem>
    <ComboBoxItem>banana</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

3.不要直接在XAML中指定项目,而是使用ItemsSourceproperty绑定到字符串集合:

<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
    ItemsSource="{Binding Fruits}"
    SelectedItem="{Binding fruit, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)