首页 > 代码库 > Winform也借MVC的TryUpdateModel一用~

Winform也借MVC的TryUpdateModel一用~

我们在使用MVC的时候,给model赋值只需要 TryUpdateModel(model) 就搞定了,而在webForm,winForm中,我们要写长长的 xx.xx = Convert.Toint( xxx.text) ...如果一个model有30个属性,就要写30行,看着都累!

这里有一篇 webForm 的文章:http://www.cnblogs.com/coolcode/archive/2009/08/15/1546936.html 借用了一下~

那winForm能否也借用呢?

我尝试写了一个扩展类(只实现了int,string,datetime类型,其它的可以扩展)

    public class Expand : Form    {        public void TryUpdateModel<TModel>(ref TModel model)        {            Type mod = model.GetType();            PropertyInfo[] property = mod.GetProperties();            object obj = Activator.CreateInstance(mod);            foreach (PropertyInfo pi in property)            {                if (Controls.ContainsKey(pi.Name))                {                    if (pi.PropertyType == typeof(DateTime))                    {                        try                        {                            pi.SetValue(obj, ((DateTimePicker)Controls[pi.Name]).Value, null);                        }                        catch { }                    }                    else if (pi.PropertyType == typeof(int))                    {                        try                        {                            pi.SetValue(obj, int.Parse(Controls[pi.Name].Text), null);                        }                        catch { }                    }                    else                    {                        try                        {                            pi.SetValue(obj, Controls[pi.Name].Text, null);                        }                        catch { }                    }                }            }            model = (TModel)obj;        }    }

  然后,我们就可以

            var model = new Class1();            this.TryUpdateModel<Class1>(ref model);

  不过,看着ref那么碍眼呢?

不知道各位大神 ~ 有没有更好点的办法

Winform也借MVC的TryUpdateModel一用~