WinForm 双向数据绑定
程序员文章站
2022-04-18 15:27:13
程序目标: 控件的属性值与对象的属性值双向绑定使窗口控件的属性值与对象的属性值保持一致。对窗口控件属性值更改后立即更新对象的属性值,对对象的属性值更改后立即更新窗口控件的属性值。 定义控件属性要绑定对象的类:Person Form: using System; using System.Diagno ......
程序目标: 控件的属性值与对象的属性值双向绑定使窗口控件的属性值与对象的属性值保持一致。对窗口控件属性值更改后立即更新对象的属性值,对对象的属性值更改后立即更新窗口控件的属性值。
定义控件属性要绑定对象的类:person
using system.componentmodel; namespace temptest { /// <summary> /// 要实现双向绑定需要继承system.componentmodel.inotifypropertychange接口。若不继承此接口则只能单向绑定,对对象属性值的更改不会通知控件更新。 /// </summary> class person : inotifypropertychanged { #region 属性 public string name { get => mname; set { mname = value; sendchangeinfo("name"); } } public string address { get => maddress; set { maddress = value;sendchangeinfo("address"); } } public int age { get => mage; set { mage = value; sendchangeinfo("age"); } } #endregion private string mname; private string maddress; private int mage; /// <summary> /// 属性改变后需要调用的方法,触发propertychanged事件。 /// </summary> /// <param name="propertyname">属性名</param> private void sendchangeinfo(string propertyname) { if (this.propertychanged != null) { propertychanged(this, new propertychangedeventargs(propertyname)); } } /// <summary> /// 实现的接口。 /// </summary> public event propertychangedeventhandler propertychanged; } }
form:
using system; using system.diagnostics; using system.windows.forms; namespace temptest { public partial class form1 : form { public form1() { initializecomponent(); } private person user; private void form1_load(object sender, eventargs e) { //创建对象初始化属性 user = new person() { name = "abc", address = "中国 湖南", age = 30 }; //绑定数据 textboxname.databindings.add("text", user, "name"); textboxaddress.databindings.add("text", user, "address"); textboxage.databindings.add("text", user, "age"); } /// <summary> /// 通过另外3个textbox改变对象属性值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonchangevalue_click(object sender, eventargs e) { user.name = textboxname2.text; user.address = textboxaddress2.text; int age; int.tryparse(textboxage2.text, out age); user.age = age; // textboxname,textboxaddress,textboxage的text会自动更新 } /// <summary> /// debug输出对象属性值 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonshow_click(object sender, eventargs e) { debug.writeline($"{user.name},{user.address},{user.age}"); } } }
上一篇: Spring Security(三)
下一篇: DEA快速生成get&set方法