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

wpf组合框中奇怪的数据绑定问题,wpf,mvvm,combobox,mvvm-light,Wpf,Mvvm,Combobox,Mvvm Light,我正在用WPF编写一个简单的GUI。目前,我在组合框中有一个静态列表,如下所示: <ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83" SelectedItem="{Binding fruit, Mode=TwoWay}"> <ComboBoxItem>apple</Combo

我正在用WPF编写一个简单的GUI。目前,我在组合框中有一个静态列表,如下所示:

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

苹果
橙色
葡萄
香蕉
我正在将SelectedItem绑定到代码中已经初始化并在其他地方使用过的单例

我在
fruit
get
上放置了一个断点,它返回“grape”,但所选项目始终为空。我甚至添加了一个按钮,以便手动调用RaisePropertyChanged,但是RaisePropertyChange调用也没有做任何事情


最后,MVVMLight提供了可混合性。没有什么重要的原因,我将组合框中的绑定从
SelectedItem
更改为
Text
,我这样做的时候,我的设计时表单就填充了预期的值,但是,当代码运行时,框继续处于空状态

您应该将
组合框.ItemSource
绑定到字符串列表(如果将项目添加到此列表中,请将字符串列表设置为
可观察集合
),然后将
水果
变量设置为字符串列表中的一个实例


我认为您遇到了问题,因为您的
fruit
变量引用的实例与您在
ComboBoxItems
列表中引用的实例不同(即使字符串相同)

这是因为在
组合框中有类型为
ComboBoxItem
的项,但要绑定到的属性类型为
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>
3.不要直接在XAML中指定项,而是使用
ItemsSource
属性绑定到字符串集合:

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


那么您如何解释问题在blend中消失?谢谢。SelectedValuePath正是我所需要的。我不想绑定ItemsSource,因为列表在发布后不会更改,并且我正在基于某些选择使用一些触发器。
<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
    ItemsSource="{Binding Fruits}"
    SelectedItem="{Binding fruit, Mode=TwoWay}"/>