關鍵字: Windows Forms, DataBindings, Nested Class, 嵌套類this
在 WinForm 中很早就已經支持數據綁定, 使用數據綁定能夠大大減小更新界面和數據的代碼.code
通常狀況下, 使用自定義的簡單對象時數據綁定能夠很好的工做, 當咱們的對象愈來愈複雜, 一個對象中使用另外一個對象做爲屬性時, 簡單的數據綁定已經沒法知足需求.orm
例若有下面兩個對象:對象
/// <summary> /// 外部實體 /// </summary> public class Outer : INotifyPropertyChanged { #region - Private - private string _name; private Inner _inner; #endregion public event PropertyChangedEventHandler PropertyChanged; public string Name { get { return this._name; } set { if(value != this._name) { this._name = value; RaisePropertyChanged(); } } } public Inner Inner { get { return this._inner; } set { if(value != this._inner) { this._inner = value; RaisePropertyChanged(); } } } private void RaisePropertyChanged([CallerMemberName]string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
/// <summary> /// 內部實體 /// </summary> public class Inner : INotifyPropertyChanged { #region - Private - private string _name; #endregion public event PropertyChangedEventHandler PropertyChanged; public string Name { get { return this._name; } set { if(value != this._name) { this._name = value; RaisePropertyChanged(); } } } private void RaisePropertyChanged([CallerMemberName]string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
數據綁定使用以下:get
//初始化對象 var outer = new Outer(); //初始化綁定對象 var outerBindingSource = new BindingSource() { DataSource = outer }; var innerBindingSource = new BindingSource(outer, nameof(outer.Inner)); //綁定到控件 this.textBoxName.DataBindings.Add("Text", outerBindingSource, nameof(outer.Name)); this.textBoxInnerName.DataBindings.Add("Text", innerBindingSource, nameof(outer.Inner.Name));
//1. 設置 ComboBox 數據源 this.comboBox.DataSource = Enum.GetValues(typeof(CustomEnum)); this.comboBox.SelectedIndex = 0; //2. 設置綁定 this.comboBox.DataBindings.Add(nameof(this.comboBox.SelectedItem), bindingSource, nameof(bindingSource.CustomEnumProperty));