数据绑定到嵌套 属性 - 无法绑定 属性 或列 (Winforms)

Databinding to nested property - Cannot bind property or column (Winforms)

我们正在 运行 使用 Windows 表单构建 .NET 4.0 应用程序。该应用程序对两种不同类型的对象使用单一表单。

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 中的 运行 时,我们得到错误

An error occured: Cannot bind to the property or column Message on the DataSource. Parameter name: dataMember

但是,如果我们安装 .NET 4.5,此错误就会消失。

这是 .NET 4.0 的限制、.NET 4.0 中的错误还是其他原因?

您可以使用以下任一选项:

B myObj = new B();
textBox1.DataBindings.Add(new Binding("Text", ((B)myObj).c, "Message"));

var bs = new BindingSource(myObj, null);
textBox1.DataBindings.Add("Text", bs, "c.Message");

textBox1.DataBindings.Add("Text", new B[] { myObj }, "c.Message");

短篇小说:Windows 表单数据绑定不支持 属性 路径,这就是您收到错误的原因。

好吧,这就是我今天一直在想的。但是尝试您的代码令我感到惊讶的是它确实 可以在.NET 4.5 机器上运行!所以看起来 MS 已经在某个时候添加了 - 老实说,不知道什么时候。但它现在就在那里!无论如何,如果向后兼容性是一个问题,那么应该避免使用该功能(尽管这会很遗憾)。