wpf - wpf 组合框中奇怪的数据绑定(bind)问题

标签 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</ComboBoxItem>
        <ComboBoxItem>orange</ComboBoxItem>
        <ComboBoxItem>grape</ComboBoxItem>
        <ComboBoxItem>banana</ComboBoxItem>
    </ComboBox>

我将 SelectedItem 绑定(bind)到代码中的单例,该单例已在其他地方初始化并使用。

我在fruitget上设置了断点,它返回“grape”,但所选项目始终为空。我什至添加了一个按钮,以便我可以手动调用 RaisePropertyChanged,但 RaisePropertyChange 调用也没有执行任何操作。

最后,MVVMLight 提供了可混合性。没有任何重要原因,我将组合框中的绑定(bind)从 SelectedItem 更改为 Text 一旦我这样做,我的设计时表单就填满了预期的值,但是,当代码正在运行,盒子继续处于空状态

最佳答案

这是因为 ComboBox 中有 ComboBoxItem 类型的项目,但您尝试绑定(bind)的属性是 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 绑定(bind)到 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属性绑定(bind)到字符串集合:

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

关于wpf - wpf 组合框中奇怪的数据绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5159708/

相关文章:

WPF:在 DataGridComboBoxColumn 中显示验证工具提示

c# - 如果对象是特定类,则检查数据触发器

wpf - MVVM Tabcontrol 更改选项卡

java - ZK Wire 组件在 @command 方法 (MVVM) 中不可访问或 View 模型不可访问 (dAft Compose MVC)

c# - 清除 ComboBox 选中的文本

c# - WPF 拖放、拖放

wpf:自定义窗口投影

c# - Xamarin MvvM 内容 View 绑定(bind)

c++ - 以编程方式更改组合框

c# - 使用平面样式更改 ToolStripComboBox 的边框