【问题标题】:WPF bind combobox selected value to a string in a view modelWPF 将组合框选定值绑定到视图模型中的字符串
【发布时间】:2017-05-20 18:33:36
【问题描述】:

我的视图中有这个组合框:

<ComboBox SelectedValue="{Binding StringObj, UpdateSourceTrigger=PropertyChanged}">
       <ComboBoxItem>string0</ComboBoxItem>
       <ComboBoxItem>string1</ComboBoxItem>
       <ComboBoxItem>string2</ComboBoxItem>
       <ComboBoxItem>string3</ComboBoxItem>
</ComboBox>

在我的视图模型中,我有这个字符串对象:

    private string _stringObj;
    public string StringObj
    {
        get { return _stringObj; }
        set { _stringObj = value; }
    }

如何将组合框中的选定值绑定到字符串变量,以便在视图模型中使用它?这是我迄今为止实现的,但它不起作用,因为我不太了解这个绑定的东西。

【问题讨论】:

  • 你有得到任何值吗? (在setter中设置断点检查,查看VS输出窗口绑定错误信息)
  • 请注意,您的 ComboBox 中的元素是 ComboBoxItems,不是字符串SelectedValue 单独不起作用(请注意,您绑定到字符串属性,这将导致绑定无法更新)。您还需要使用 SelectedValuePath 属性来指定包含字符串(即 Content)的 ComboBoxItem 对象的属性。
  • 你为什么不赞成我的回答?它为您的问题提供了准确的解决方案。您可以或多或少地按原样复制和粘贴...?

标签: c# wpf data-binding combobox


【解决方案1】:

您不能将 string 属性设置为 ComboBoxItem 值。

您可以在 XAML 中将 ComboBoxItems 替换为 strings 并绑定 SelectedItem 属性:

<ComboBox SelectedItem="{Binding StringObj, UpdateSourceTrigger=PropertyChanged}"
          xmlns:s="clr-namespace:System;assembly=mscorlib">
    <s:String>string0</s:String>
    <s:String>string1</s:String>
    <s:String>string2</s:String>
    <s:String>string3</s:String>
</ComboBox>

或者您可以简单地将SelectedValuePath 属性设置为“内容”:

<ComboBox SelectedValue="{Binding StringObj, UpdateSourceTrigger=PropertyChanged}"
          SelectedValuePath="Content">
    <ComboBoxItem>string0</ComboBoxItem>
    <ComboBoxItem>string1</ComboBoxItem>
    <ComboBoxItem>string2</ComboBoxItem>
    <ComboBoxItem>string3</ComboBoxItem>
</ComboBox>

这会将您的源属性设置为所选ComboBoxItemContent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2012-05-05
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多