ComboBox没有更新所选项目上的DataBindings更改(WinForms)

kbe*_*l2k 6 c# data-binding winforms

我有一个绑定到数据源的ComboBox但它不会更新绑定,直到控件失去焦点.如何在所选项目更改时获取更新绑定?在下面的屏幕截图中,我希望标签立即更新以反映新的选择.

一些代码:

public enum MyEnum
{
  First,
  Second
}

public class MyData
{
  public String Name { get; set; }
  public MyEnum MyEnum { get; set; }
}  
Run Code Online (Sandbox Code Playgroud)

样品表格:

public SampleForm()
{
  InitializeComponent ();   
  MyData data = new MyData () { Name = "Single Item" };
  this.bindingSource1.DataSource = data;
  this.comboBox1.DataSource = Enum.GetValues (typeof (MyEnum));
  this.label2.DataBindings.Add ("Text", this.bindingSource1, "MyEnum", true, DataSourceUpdateMode.OnPropertyChanged);
  this.comboBox1.DataBindings.Add (new System.Windows.Forms.Binding ("SelectedItem", this.bindingSource1, "MyEnum", true));
  this.comboBox1.DataBindings.Add (new System.Windows.Forms.Binding ("SelectedValue", this.bindingSource1, "MyEnum", true));
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ech 10

注释掉SelectedItem版本,并像这样修改SelectedValue绑定以包含UpdateMode:

this.comboBox1.DataBindings.Add(new Binding(
                                      "SelectedValue",
                                      this.bindingSource1,
                                      "MyEnum",
                                      true,
                                      DataSourceUpdateMode.OnPropertyChanged));
Run Code Online (Sandbox Code Playgroud)


mgg*_*oft 5

LarsTech 的解决方案是正确的。您也可以在设计模式下执行此操作:

  1. 组合框属性 (F4) -> 数据绑定节点 -> 高级

  1. 单击“SelectedValue”并将数据源更新模式更改为“OnPropertyChanged” 在此输入图像描述