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

时间:2011-03-01 20:05:17

标签: wpf mvvm combobox 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>

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

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

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

2 个答案:

答案 0 :(得分:5)

这是因为ComboBoxItem中有ComboBox类型的项目,但您尝试绑定的属性属于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>

2.而不是SelectedItem绑定到SelectedValue并将SelectedValuePath指定为Content

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

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}"/>

答案 1 :(得分:1)

您应该将ComboBox.ItemSource绑定到字符串列表(如果您将项添加到此列表中,则将字符串列表设为ObservableCollection<string>),然后将fruit变量设置为实例在字符串列表中。

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

相关问题