程序目標: 控件的屬性值與對象的屬性值雙向綁定使窗口控件的屬性值與對象的屬性值保持一致。對窗口控件屬性值更改后立即更新對象的屬性值,對對象的屬性值更改后立即更新窗口控件的屬性值。
程序完整代碼包:https://pan.baidu.com/s/1JPX0BJDNiEoczYE9xXL1ow
主要代碼:
定義控件屬性要綁定對象的類: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}"); } } }