数据绑定到对象 - 如何更新对象/绑定?

Tro*_*ond 4 .net c# data-binding winforms

我有一个文本框并使用数据绑定到一个对象.这很好,直到我尝试选择一个新产品:

product = new Product(id);
textbox.DataBindings.Add("Text", product, "ProductName");

// After user action:
product = new Product(newId); // <- the textbox isn't updated
Run Code Online (Sandbox Code Playgroud)

产品更新后,是否必须清除数据绑定并再次设置?

Oli*_*ver 8

简而言之:是的,您必须重新建立DataBinding,因为TextBox具有对旧对象的引用.

但为了使其更加健壮,您应该为DataBinding使用BindingSource.要使其工作,您应该在设计视图中打开表单.

  • 选择TextBox并打开"属性"窗口
  • 查看类别数据,然后单击(DataBindings)属性左侧的叉号
  • 单击Text属性旁边的下拉按钮
  • 在下拉列表中,选择添加项目数据源
  • 从向导中选择Object,然后在下一个对象类型中选择

现在,您将在表单中获得一个新对象(例如productBindingSource),该对象绑定到TextBox的文本.最后但并非最不重要的是,您必须使用以下代码附加您的对象:

productBindingSource.DataSource = product;
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案也不能帮助重新绑定,但你现在要做的就是:

product = new Product();
productBindingSource.DataSource = product;
Run Code Online (Sandbox Code Playgroud)