数据绑定到嵌套属性-无法绑定属性或列(Winforms)
我们正在使用Windows窗体运行.NET 4.0应用程序。该应用程序对两种不同类型的对象使用单一形式。
We are running a .NET 4.0 application using Windows Forms. The application uses a single form for two different types of objects.
namespace NetIssue
{
public partial class Form1 : Form
{
B myObj;
public Form1()
{
InitializeComponent();
myObj = new B();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add(new Binding("Text", myObj, "c.Message"));
}
}
public class Comment {
public int ID { get; set; }
public string Message { get; set; }
public Comment(string msg)
{
Message = msg;
}
}
public class A {
string MyName = "";
}
public class B : A {
public Comment c { get; set; }
public B()
{
c = new Comment("test");
}
}
}
运行上面的绑定时在.NET 4.0中,我们得到错误
When the binding above is run in .NET 4.0, we get the error
发生了一个错误:无法绑定到
DataSource上的属性或Message列。参数名称:dataMember
An error occured: Cannot bind to the property or column Message on the DataSource. Parameter name: dataMember
但是,如果我们安装.NET 4.5,此错误将消失。
However, if we install .NET 4.5 this error goes away.
这是.NET 4.0的限制吗,.NET 4.0中的错误,还是其他情况?
短篇小说:Windows Forms数据绑定不支持属性路径,这就是为什么出现错误的原因。
Short story: Windows Forms data binding doesn't support property path, that's why you are getting the error.
嗯,这就是我直到今天才想到的。但是尝试您的代码时,我很惊讶它确实可在.NET 4.5机器上运行!看来MS补充了一点-老实说,不知道何时。但是现在在那里!无论如何,如果要考虑向后兼容性,则应该避免使用该功能(尽管很遗憾)。
Well, this is what I was thinking until today. But trying your code I was surprised that it indeed works on .NET 4.5 machine! So looks like MS has added that at some point - to be honest, have no idea when. But it's there now! Anyway, if backward compatibility is a concern, one should avoid using that feature (although it would be quite pity).