我有一个文本框并使用数据绑定(bind)到一个对象。这工作正常,直到我尝试选择一个新产品:
product = new Product(id);
textbox.DataBindings.Add("Text", product, "ProductName");
// After user action:
product = new Product(newId); // <- the textbox isn't updated
是否必须在产品更新后清除数据绑定(bind)并重新设置?
最佳答案
简而言之:是的,您必须重新建立 DataBinding,因为 TextBox 具有对旧对象的引用。
但是为了使它更健壮一些,您也许应该为您的 DataBinding 使用 BindingSource。要使其正常工作,您应该在设计 View 中打开表单。
- 选择您的文本框并打开“属性”窗口
- 查看类别Data 并单击(DataBindings) 属性左侧的叉号
- 点击文本属性旁边的下拉按钮
- 在下拉列表中选择添加项目数据源
- 从向导中选择对象,然后在接下来选择您的对象类型
现在您将在表单中获得一个新对象(例如 productBindingSource),该对象绑定(bind)到您的 TextBox 的文本。最后但同样重要的是,您必须使用以下代码附加您的对象:
productBindingSource.DataSource = product;
但此解决方案也无助于重新绑定(bind),但您现在要做的是:
product = new Product();
productBindingSource.DataSource = product;
关于c# - 数据绑定(bind)到对象 - 如何更新对象/绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004731/