用反射写的数据绑定

数据绑定感觉挺神奇的,但是也有些局限性,似乎只能绑定DataTable一类的东西。至于数据绑定的原理,也没查过,个人感觉是反射。基于其局限性和反射技术,自己写了个用反射原理作成的数据绑定。

 

当然是写一个扩展TextBox的新的控件

  1. public partial class UserTextBox : TextBox

实现方法

  1.         /// 
  2.         /// Use Reflect to implement DataBind
  3.         /// 
  4.         /// Property of the UserTextBox
  5.         /// DataSource of the binding data
  6.         /// Binding which property of the DataSource
  7.         public void DataBindExtend(string propertyName, object dataSource, string dataNumber)
  8.         {
  9.             //Get the type of traget & source
  10.             Type type = typeof(UserTextBox);
  11.             Type typeCont = dataSource.GetType();
  12.             try
  13.             {
  14.                 //Get the property of traget and source
  15.                 PropertyInfo tragetInfo = type.GetProperty(propertyName);
  16.                 PropertyInfo sourceInfo = typeCont.GetProperty(dataNumber);
  17.                 //Get the value of source
  18.                 object sourceValue = sourceInfo.GetValue(dataSource, null);
  19.                 //Set the value to the traget
  20.                 tragetInfo.SetValue(this, sourceValue, null);
  21.             }
  22.             catch (AmbiguousMatchException)
  23.             {
  24.             }
  25.         }

你可能感兴趣的:(了无秘密,textbox,null,扩展)