• 实体与UI的互相绑定


     在程序开发过程中,常常会遇到从窗体上获取信息赋值给对应的实体,或者把实体信息赋值给窗体上的控件,

     为了避免写太多重复的代码,封装成一个类来实现。

     1     public class MyKeyValue
     2     {
     3         public object MyKey
     4         {
     5             get;
     6             set;
     7         }
     8 
     9         public object MyValue
    10         {
    11             get;
    12             set;
    13         }
    14 
    15         public MyKeyValue(object key, object value)
    16         {
    17             MyKey = key;
    18             MyValue = value;
    19         }
    20     }
    View Code
      1 /// <summary>
      2         /// 根据模型的属性名查找控件,。
      3         /// </summary>
      4         /// <param name="container">控件容器</param>
      5         /// <param name="propertyName">控件名称</param>
      6         /// <returns></returns>
      7         private static Control FindControl(Control container, string propertyName)
      8         {
      9             Control control = null;
     10 
     11             //考虑有些控件放在窗体的容器中,采用了递归查找
     12             foreach (Control ctr in container.Controls)
     13             {
     14                 if (!string.IsNullOrEmpty(ctr.Name))
     15                 {
     16                     //排除控件3个字符的前缀
     17                     if (ctr.Name.Substring(3) == propertyName)
     18                     {
     19                         return ctr;
     20                     }
     21 
     22                     control = FindControl(ctr, propertyName);
     23                     if (control != null)
     24                     {
     25                         return control;
     26                     }
     27                 }
     28             }
     29 
     30             return control;
     31         }
     32 
     33         /// <summary>
     34         /// 从窗体中获取模型
     35         /// </summary>
     36         /// <typeparam name="T">模型的类型</typeparam>
     37         /// <param name="container">窗体或控件容器</param>
     38         /// <returns>模型</returns>
     39         public static T GetModel<T>(this Control container) where T : new()
     40         {
     41             T model = new T();
     42 
     43             //获取业务对象的属性   
     44             foreach (PropertyInfo modelProperty in model.GetType().GetProperties())
     45             {
     46                 Control control = FindControl(container, modelProperty.Name);
     47 
     48                 if (control == null)
     49                 {
     50                     continue;
     51                 }
     52 
     53                 if (control is Label)
     54                 {
     55                     Label label = (Label)control;
     56                     modelProperty.SetValue(model, Convert.ChangeType(label.Text, modelProperty.PropertyType), null);
     57                     goto myContinue;
     58                 }
     59                 else if (control is TextBox)
     60                 {
     61                     TextBox textBox = (TextBox)control;
     62                     modelProperty.SetValue(model, Convert.ChangeType(textBox.Text, modelProperty.PropertyType), null);
     63                     goto myContinue;
     64                 }
     65                 else if (control is NumericUpDown)
     66                 {
     67                     NumericUpDown nud = (NumericUpDown)control;
     68                     modelProperty.SetValue(model, Convert.ChangeType(nud.Value, modelProperty.PropertyType), null);
     69                     goto myContinue;
     70                 }
     71                 else if (control is DateTimePicker)
     72                 {
     73                     DateTimePicker dateTimePicker = (DateTimePicker)control;
     74                     modelProperty.SetValue(model, Convert.ChangeType(dateTimePicker.Value, modelProperty.PropertyType), null);
     75                     goto myContinue;
     76                 }
     77                 else if (control is CheckBox)
     78                 {
     79                     CheckBox checkBox = (CheckBox)control;
     80                     modelProperty.SetValue(model, Convert.ChangeType(checkBox.Checked, modelProperty.PropertyType), null);
     81                     goto myContinue;
     82                 }
     83                 else if (control is ComboBox)
     84                 {
     85                     ComboBox comboBox = (ComboBox)control;
     86                     modelProperty.SetValue(model, Convert.ChangeType(comboBox.SelectedValue, modelProperty.PropertyType), null);
     87                     goto myContinue;
     88                 }              
     89                 else if (control is DataGridView)
     90                 {
     91                     DataGridView dgv = (DataGridView)control;
     92 
     93                     IList list = model.GetType().GetProperty(modelProperty.Name).GetValue(model, null) as IList;
     94                     Type[] itemTypes = model.GetType().GetProperty(modelProperty.Name).PropertyType.GetGenericArguments();
     95                     Type itemType = itemTypes[0];
     96 
     97                     int i = 0;
     98                     foreach (DataGridViewRow row in dgv.Rows)
     99                     {
    100                         object item = Activator.CreateInstance(itemType);
    101                         foreach (PropertyInfo itemModelProperty in itemType.GetProperties())
    102                         {
    103                             object val = dgv.Rows[i].Cells[itemModelProperty.Name].Value;
    104                             itemType.GetProperty(itemModelProperty.Name).SetValue(item, Convert.ChangeType(val, itemModelProperty.PropertyType), null);
    105                         }
    106                         list.Add(item);
    107                         i++;
    108                     }
    109                 }
    110             myContinue:
    111                 continue;
    112             }
    113   
    114 
    115             return model;
    116         }
    117 
    118         /// <summary>
    119         /// 从窗体中获取模型
    120         /// </summary>
    121         /// <typeparam name="T">模型的类型</typeparam>
    122         /// <param name="container">窗体或控件容器</param>
    123         /// <returns>模型</returns>
    124         /// <param name="dirControl">Dictionary<属性名,Dictionary<属性值,控件名>></param>
    125         public static T GetModelEx<T>(this Control container, Dictionary<string, IList<MyKeyValue>> dirControl) where T : new()
    126         {
    127             T model =GetModel<T>(container);
    128             //获取业务对象的属性   
    129             foreach (PropertyInfo modelProperty in model.GetType().GetProperties())
    130             {
    131                 if (dirControl.ContainsKey(modelProperty.Name))
    132                 {
    133                     IList<MyKeyValue> list = dirControl[modelProperty.Name];
    134 
    135                     foreach (MyKeyValue item in list)
    136                     {
    137                         Control control = FindControl(container, item.MyValue.ToString());
    138 
    139                         if (control == null)
    140                         {
    141                             continue;
    142                         }
    143                         if (control is RadioButton)
    144                         {
    145                             RadioButton radio = (RadioButton)control;
    146                             modelProperty.SetValue(model, Convert.ChangeType(item.MyKey, modelProperty.PropertyType), null);
    147                             //modelProperty.SetValue(model, Convert.ChangeType(radio.Checked, modelProperty.PropertyType), null);
    148                             if (radio.Checked&&modelProperty.GetValue(model, null) != null)
    149                                 goto myContinue;
    150                         } 
    151                     }
    152                 myContinue:
    153                     continue;
    154                 }
    155             }
    156             return model;
    157         }
    158 
    159         /// <summary>
    160         /// 将模型绑定到窗体或控件容器
    161         /// </summary>
    162         /// <typeparam name="T">模型类型</typeparam>
    163         /// <param name="container">窗体或控件容器</param>
    164         /// <param name="model">模型</param>
    165         public static bool SetModel<T>(this Control container, T model)
    166         {
    167             if (model == null)
    168             {
    169                 return false;
    170             }
    171             int result = 0;
    172             foreach (PropertyInfo modelProperty in model.GetType().GetProperties())
    173             {
    174                 Control control = FindControl(container, modelProperty.Name);
    175                 if (control == null)
    176                 {
    177                     continue;
    178                 }
    179                 
    180                 if (control is Label)
    181                 {
    182                     Label label = (Label)control;
    183                     label.Text = modelProperty.GetValue(model, null) == null ? string.Empty : modelProperty.GetValue(model, null).ToString();
    184                     result += 1;
    185                     goto myContinue;
    186                 }
    187                 else if (control is TextBox)
    188                 {
    189                     TextBox textBox = (TextBox)control;
    190                     textBox.Text = modelProperty.GetValue(model, null) == null ? string.Empty : modelProperty.GetValue(model, null).ToString();
    191                     result += 1;
    192                     goto myContinue;
    193                 }
    194                 else if (control is DateTimePicker)
    195                 {
    196                     DateTimePicker dateTimePicker = (DateTimePicker)control;
    197                     dateTimePicker.Value = Convert.ToDateTime(modelProperty.GetValue(model, null));
    198                     result += 1;
    199                     goto myContinue;
    200                 }
    201                 else if (control is NumericUpDown)
    202                 {
    203                     NumericUpDown nud = (NumericUpDown)control;
    204                     nud.Value = Convert.ToInt32(modelProperty.GetValue(model, null));
    205                     result += 1;
    206                     goto myContinue;
    207                 }
    208                 else if (control is CheckBox)
    209                 {
    210                     CheckBox checkBox = (CheckBox)control;
    211                     checkBox.Checked = Convert.ToBoolean(modelProperty.GetValue(model, null));
    212                     result += 1;
    213                     goto myContinue;
    214                 }
    215                 else if (control is ComboBox)
    216                 {
    217                     ComboBox comboBox = (ComboBox)control;
    218                     comboBox.SelectedValue = (modelProperty.GetValue(model, null));
    219                     result += 1;
    220                     goto myContinue;
    221                 }
    222                 else if (control is DataGridView)
    223                 {
    224                     DataGridView dgv = (DataGridView)control;
    225 
    226                     object listPropertyValue = model.GetType().GetProperty(modelProperty.Name).GetValue(model, null);
    227 
    228                     IList list = listPropertyValue as IList;
    229                     if (list != null)
    230                     {
    231                         int i = 0;
    232                         dgv.Rows.Clear();
    233 
    234                         foreach (object o in list)
    235                         {
    236                             dgv.Rows.Add(1);
    237 
    238                             Type itemType = o.GetType();
    239                             foreach (PropertyInfo itemModelProperty in itemType.GetProperties())
    240                             {
    241                                 
    242                                 object val = itemType.GetProperty(itemModelProperty.Name).GetValue(o, null);
    243                                 if (dgv.Columns.Contains(itemModelProperty.Name))
    244                                 {
    245                                     dgv.Rows[i].Cells[itemModelProperty.Name].Value = val.ToString();    
    246                                 }
    247                             }
    248 
    249                             i++;
    250                         }
    251                     }
    252                     result += 1;
    253                 }
    254                myContinue:
    255                 continue;
    256             }
    257             return result == model.GetType().GetProperties().Count();
    258         }
    259 
    260 
    261         /// <summary>
    262         /// 将模型绑定到窗体或控件容器拓展方法
    263         /// 主要是拓展关于属性值比较多  比如状态,性别,类型情况下单选
    264         /// </summary>
    265         /// <typeparam name="T">模型类型</typeparam>
    266         /// <param name="container">窗体或控件容器</param>
    267         /// <param name="model">模型</param>
    268         /// <param name="dirControl">Dictionary<属性名,Dictionary<属性值,控件名>></param>
    269         public static void SetModelEx<T>(this Control container, T model, Dictionary<string, IList<MyKeyValue>> dirControl)
    270         {
    271             if (model == null)
    272             {
    273                 return;
    274             }
    275             bool result = SetModel(container, model);
    276             if (false == result)
    277             {
    278                 foreach (PropertyInfo modelProperty in model.GetType().GetProperties())
    279                 {
    280                     if (!dirControl.ContainsKey(modelProperty.Name))
    281                     {
    282                         continue;
    283                     }
    284                     foreach (MyKeyValue kvp in dirControl[modelProperty.Name])
    285                     {
    286                         Control control = FindControl(container, kvp.MyValue.ToString());
    287                         if (control == null)
    288                         {
    289                             continue;
    290                         }                       
    291                         if (control is RadioButton)
    292                         {
    293                             string value = modelProperty.GetValue(model, null) == null ? string.Empty : modelProperty.GetValue(model, null).ToString();
    294                             if (value != string.Empty)
    295                             {
    296                                 RadioButton radButton = (RadioButton)control;
    297                                 radButton.Checked = modelProperty.GetValue(model, null).ToString() == kvp.MyKey.ToString();
    298                                 if(radButton.Checked)
    299                                     goto myContinue;
    300                             }
    301                         }
    302                     }
    303                 myContinue:
    304                     continue;
    305                 }
    306             }
    307         }
    View Code


    方法名以Ex结尾的是在原有实现的基础上再实现多类型单选,比如说 性别(男女),类型(有效,无效)等一个属性对应多个控件的功能

    控件赋值给实体调用方式:

     1     /// <summary>
     2     /// 学生信息
     3     /// </summary>
     4     public class StudentInfo
     5     {
     6         /// <summary>
     7         /// 性别
     8         /// </summary>
     9         public string Sex
    10         {
    11             get;
    12             set;
    13         }
    14         /// <summary>
    15         /// 姓名
    16         /// </summary>
    17         public string Name
    18         {
    19             get;
    20             set;
    21         }
    22     }  
    23 
    24 Dictionary<string, IList<MyKeyValue>> dirControl = new Dictionary<string, IList<MyKeyValue>>();
    25             IList<MyKeyValue> list = new List<MyKeyValue>();
    26             list.Add(new MyKeyValue("1", "Sex男"));
    27             list.Add(new MyKeyValue("0", "Sex女"));
    28             dirControl.Add("Sex", list);
    29             StudentInfo model = new StudentInfo();
    30             model=FormBinding.GetModelEx<StudentInfo>(this, dirControl);
    View Code

    实体赋值给控件调用方式:

    1  StudentInfo model=new StudentInfo(){Sex="0",Name="TEST"};
    2             Dictionary<string, IList<MyKeyValue>> dirControl = new Dictionary<string, IList<MyKeyValue>>();
    3             IList<MyKeyValue> list = new List<MyKeyValue>();
    4             list.Add(new MyKeyValue("1","Sex男"));
    5             list.Add(new MyKeyValue("0", "Sex女"));
    6             dirControl.Add("Sex", list);
    7             FormBinding.SetModelEx(this, model, dirControl);
    View Code

     
      以上只做了简单的封装,有更好的实现方式欢迎推荐!

  • 相关阅读:
    ACM实用C语言函数
    Java中的数组和方法
    eclipse常用快捷键
    【转载】第十章 五种对称加密算法总结
    【转载】ZooKeeper学习第二期--ZooKeeper安装配置
    【转载】Java垃圾回收机制
    【转载】JVM系列三:JVM参数设置、分析
    【转载】JVM系列二:GC策略&内存申请、对象衰老
    【转载】JVM系列一:JVM内存组成及分配
    java项目性能测试过程记录
  • 原文地址:https://www.cnblogs.com/AllUserBegin/p/3547904.html
Copyright © 2020-2023  润新知