【问题标题】:Winforms ComboBox 2 way databinding only works 1 wayWinforms ComboBox 2 方式数据绑定仅适用于 1 方式
【发布时间】:2013-05-15 05:09:05
【问题描述】:

我有一个组合框,在设计视图中我将它数据绑定到绑定源,如下所示:

this.itemTypeComboBox.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.itemTypeContainerBindingSource, "ItemType", true));
this.itemTypeComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.itemTypeContainerBindingSource, "ItemType", true));

在加载事件后面的代码中,我有以下内容:

// bind the combobox to the enum
this.itemTypeComboBox.DataSource = Enum.GetValues(typeof(OpticalItemType));

// bind a custom object to the datasource
this.itemTypeContainerBindingSource.DataSource = customObjectContainer;

“customObjectContainer”是一个单独的对象,包含一个绑定到组合框的属性“ItemType”,并且该对象的所有属性都通过“INotifyPropertyChanged”使用更改通知。

在我后面的代码中,如果我以编程方式更改自定义对象,更改会反映在组合框中。但是,如果我通过 UI 更改组合框,则绑定源以及自定义对象不会反映更改。

任何想法我做错了什么?

因为它是一个单一的对象,所以它不能与使用BindingList等有关。

更新 1:

好的,每当我通过 UI 更改组合框时,它永远不会更改底层对象,永远不会为自定义对象中的属性命中 setter。但是,我刚刚注意到,如果我关闭控件,它会触发 setter,并更改底层对象。为什么会这样?

问题已解决:

看来,问题出在我的绑定上。我在绑定中添加了“DataSourceUpdateMode.OnPropertyChanged”,它现在可以工作了!!

【问题讨论】:

  • “ItemType”的类型是什么?也许当组合框中的选定值发生更改时,它会尝试将字符串分配给枚举,反之亦然。
  • “ItemType”是“OpticalItemType”的枚举实例
  • 它有一个公共的setter?
  • 是的,它有一个公共的 getter 和 setter
  • 遇到了一些问题,问题已更新

标签: winforms data-binding


【解决方案1】:

问题在于我的绑定。我在绑定中添加了“DataSourceUpdateMode.OnPropertyChanged”,它现在可以工作了!!

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多