關於databinding的細節

原文在此:http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorialhtml

完整譯文在此:http://www.cnblogs.com/lichence/archive/2012/02/17/2356001.html數據庫

譯不下去的筆記在此:編碼

System.Windows.Forms.BindingSource是2.0裏邊的一個新類。趕腳微軟想用BindingSource取代之前的CurrencyManager和BindingContext,因此本篇就只講講BingdingSource。code

首先:orm

  • Control.DataBindings集合持有全部Binding的對象,每一個Binding的對象都有一個屬性DataSource,用來標明Object的type;  
  • ListBox/DataGridView等的DataSource,能夠是Object  
  • BindingSource類,有DataSource屬性。

so,DataSource究竟是幹嗎的?……在現實編碼中,一般用BindingSource實例做爲Bindings對象們的DataSource屬性的值,Binddings[x].DataSource is BindingSource。htm

若是你用數據庫,那麼這個BindingSource.DataSource一般是DataSet,若是不用數據庫,那它極可能是一個自定義類的實例。對象

使用data binding的方法千千萬,最經常使用之一:給一個Control的DataSource綁一個BindingSource對象。  blog

能夠認爲BindingSource是一個二合一的數據源。二合一一般意味着:   事件

  1. 有一個叫Current的Object實例,Control的某屬性能夠綁定到這個Current對象的某屬性上。   
  2. 有一個實現了IList的列表,裏邊全是和Current同樣類型的對象。List是BindingSource的只讀屬性,用來返回一個內部列表(若是沒設置DataMember的話),或者返回一個外部列表(若是設置了DataMember)。Current老是這個List的一員,要麼是null。當設置該DataSource爲一個單一的實例時,這個列表就只包含這個惟一的Object。

控件不一樣數據綁定的方式也有不一樣:   ip

  1. ComboBox和ListBox使用DataSource和DisplayMember綁定一個List。先將DataSource賦值爲BindingSource對象,而後設置DisplayMember屬性爲Current的某個屬性。   
  2. DataGrid和DataGridView使用DataSource屬性綁定一個List。這倆控件沒有DisplayMember屬性。DataGridView有一個DataMember的屬性,它看起來和BindingSource的DataMember很類似。若是DataSource不是BindingSource的話,就要用DataGridView.DataMember來設置數據源。若是DataSource是BindingSource,仍是得用BindingSource的DataMember。   
  3. TextBox/Button/CheckBox這類簡單的控件,經過Control.DataBindings集合將自身綁定到數據源的Current對象的某一屬性上。   

      * grid什麼的它們的DataBindings屬性,即便有東西,也是無用的。這個要注意。

再簡化一下也就是兩種綁定方式,一個是經過Control.DataSource=,一個是Control.DataBindings.Add()。

經常使用於綁定的屬性包括:   

  1. CheckBox和RadioButton的Checked;   
  2. ComboBox/ListBox/ListView的SelectedIndex   
  3. ComboBox/ListBox的SelectedValue   
  4. 控件的Enable/Visible   
  5. 控件的Text

Tips: ListView和TreeView的內容是不能綁定的(天怒人怨),它的SelectIndex和Enable這樣的屬性能夠綁定。(天怒人怨)

……

 •The latter handler (Binding.Target_Validate) passes the new value through a couple of internal classes, BindToObject and ReflectPropertyDescriptor, the latter of which uses Reflection to actually change the value in the Airplane and then call base.OnValueChanged in its base class, PropertyDescriptor.

這裏貌似是講到TextBox的Validate事件才傳新值進行binding的同步。(相關:爲何只有textbox lose focus之後,數據纔會刷新??)

txtModel.DataBindings[0].DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;

默認值是OnValidated

相關文章
相關標籤/搜索