資料繫結感覺挺神奇的,但是也有些局限性,似乎只能綁定DataTable一類的東西。至於資料繫結的原理,也沒查過,個人感覺是反射。基於其局限性和反射技術,自己寫了個用反射原理作成的資料繫結。
當然是寫一個擴充TextBox的新的控制項
- public partial class UserTextBox : TextBox
實現方法
- /// <summary>
- /// Use Reflect to implement DataBind
- /// </summary>
- /// <param name="propertyName">Property of the UserTextBox</param>
- /// <param name="dataSource">DataSource of the binding data</param>
- /// <param name="dataNumber">Binding which property of the DataSource</param>
- public void DataBindExtend(string propertyName, object dataSource, string dataNumber)
- {
- //Get the type of traget & source
- Type type = typeof(UserTextBox);
- Type typeCont = dataSource.GetType();
- try
- {
- //Get the property of traget and source
- PropertyInfo tragetInfo = type.GetProperty(propertyName);
- PropertyInfo sourceInfo = typeCont.GetProperty(dataNumber);
- //Get the value of source
- object sourceValue = sourceInfo.GetValue(dataSource, null);
- //Set the value to the traget
- tragetInfo.SetValue(this, sourceValue, null);
- }
- catch (AmbiguousMatchException)
- {
- }
- }