Setup:
- 类
Model
具有一个类型为接口(interface)的属性。 - 创建实例并将其添加到 winforms 绑定(bind)源
- 将文本框添加到 winforms 并将文本值配置为使用具有属性的绑定(bind)源作为数据成员
Model
public class Model
{
public ICustomer Customer { get; set; }
}
public class Customer : ICustomer
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
public interface ICustomer
{
string Name { get; set; }
}
Binding
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bsModel, "Customer", true));
Problem
当我运行这段代码时,文本框保持为空(而不是显示客户的姓名)。
但是当我将 Model 中的 Customer 属性的类型更改为具体的 Customer 类型时,它确实显示了它。
我在 MSDN 上找不到任何原因,这是为什么?有什么想法吗?
(最好不要像将 toString 值存储到另一个属性中这样的解决方法,有一个框架可以执行此绑定(bind),我不想侵入)
最佳答案
可能您应该指定应该绑定(bind)到 TextBox 的 Text 属性的属性
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding
("Text", this.bsModel, "Customer.Name", true));
如果您删除接口(interface) ICustomer 并直接使用具体类 Customer,那么绑定(bind)代码将使用您在具体类中覆盖的一直存在的 ToString() 方法,从而设置文本框。
例如,尝试更改 ToString 以返回 Surname 属性
关于c# - Winforms Bindingsource Datamember 属性界面什么都不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515184/