简体   繁体   English

如何将字段绑定到 WinForms 中的控件?

[英]How do I bind a field to a control in WinForms?

Assume there is a class Person {Name} and we want to bind the name of the person to a textbox.text property.假设有一个 class Person {Name},我们想将这个人的名字绑定到 textbox.text 属性。 How is this accomplished?这是如何实现的?

something similar to:类似于:

nameTextbox.DataBindings.Add(...)

I have done this in WPF using DepedencyProperties but haven't find anything similar to WinForms我已经在 WPF 中使用 DepedencyProperties 完成了此操作,但没有找到类似于 WinForms 的任何内容

This is amazingly simple.这非常简单。 Seems to be working out of the box.似乎开箱即用。 I must bee blind for not figuring this earlier我一定是瞎了眼,因为没有早点想到这一点

Person person1 = new Person();
person1.Name = "Odys";
textbox.DataBindings.Add("Text", person1, "Name");

Works just fine!工作得很好!

You need to create a BindingSource and use the Person instance as DataSource for this.为此,您需要创建一个BindingSource并将 Person 实例用作 DataSource。 Then you have to bind the TextBox Text Property to the BindingSource.然后您必须将 TextBox 文本属性绑定到 BindingSource。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM