【问题标题】:Weird databinding issues in wpf comboboxwpf组合框中奇怪的数据绑定问题
【发布时间】:2011-07-06 19:01:59
【问题描述】:

我正在编写 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 绑定到我的代码中已经初始化并在其他地方使用的单例。

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

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

【问题讨论】:

    标签: wpf mvvm combobox mvvm-light


    【解决方案1】:

    这是因为您在 ComboBox 中有 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>
    

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

    【讨论】:

    • 谢谢。 SelectedValuePath 正是我所需要的。我不想绑定 ItemsSource,因为列表在发布后不会更改,而且我正在使用基于某些选择的触发器。
    【解决方案2】:

    您应该将ComboBox.ItemSource 绑定到字符串列表(将字符串列表设为ObservableCollection&lt;string&gt;,以防您将项目添加到此列表中),然后将fruit 变量设置为字符串列表中的实例。

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

    【讨论】:

    • 那你如何解释问题在 blend 内部消失了?
    猜你喜欢
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多