我正在 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)到代码中的单例,该单例已在其他地方初始化并使用。
我在fruit
的get
上设置了断点,它返回“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/