`
lovnet
  • 浏览: 6671347 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

WinForm中使用反射将业务对象绑定到窗体或控件容器

阅读更多

在WebForm中,可以使用反射将业务对象绑定到 ASP.NET 窗体控件。最近做Winform项目,也参考WebForm中的代码实现同样的功能。

Winform没有提供类似WebForm中的FindControl方法,我于是用遍历控件的方式,写了一个类似WebForm中的这个方法,考虑到Winform中的很多控件放在Label、TabControl中,方法采用了递归的方式。

Winform和Winform的控件也有些区别,如在Winform中,DateTimePicker取值是用Value属性,在WebForm中使用SelectDate属性,在Winform中,有NumericUpDown控件,取值也是用Value属性,因此,具体绑定方式上也和WebForm中有些区别。

////代码如下:
using System;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;

namespace BindTest
{

public sealed class FormBinding
{
/// <summary>
/// 将业务对象绑定到窗体或控件容器
/// </summary>
/// <param name="obj">业务对象</param>
/// <param name="container">窗体或控件容器</param>
public static void BindObjectToControls(object obj, Control container)
{
if (obj == null) return;

Type objType = obj.GetType();
PropertyInfo[] objPropertiesArray = objType.GetProperties();

foreach (PropertyInfo objProperty in objPropertiesArray)
{
Control control = FindControl(container, objProperty.Name);
if (control == null) continue;

if (control is DateTimePicker)
{
DateTimePicker dateTimePicker = (DateTimePicker)control;
dateTimePicker.Value = (DateTime)objProperty.GetValue(obj, null);
}
else
{
//获取控件的属性
Type controlType = control.GetType();
PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

//通用属性
bool success = false;
success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));

if (!success)
success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

if (!success)
success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

if (!success)
success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedValue", typeof(String));

}
}
}


/// <summary>
/// 根据控件名找出容器中的控件,考虑有些控件放在窗体的容器中,采用了递归查找。
/// </summary>
/// <param name="container">控件容器</param>
/// <param name="controlName">控件名称</param>
/// <returns></returns>
private static Control FindControl(Control container, string controlName)
{
Control findControl = null;
foreach(Control control in container.Controls)
{
if (control.Controls.Count == 0)
{
if (control.Name == controlName)
{
findControl = control;
break;
}
}
else
{
findControl = FindControl(control, controlName);
}
}
return findControl;
}

/// <summary>
/// 设置控件的值
/// </summary>
/// <param name="obj"></param>
/// <param name="objProperty"></param>
/// <param name="control"></param>
/// <param name="controlPropertiesArray"></param>
/// <param name="propertyName"></param>
/// <param name="type"></param>
/// <returns></returns>
private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
{
foreach (PropertyInfo controlProperty in controlPropertiesArray)
{
if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
{
controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
return true;
}
}
return false;
}

public static void BindControlsToObject(object obj, Control container)
{
if (obj == null) return;

//获取业务对象的属性
Type objType = obj.GetType();
PropertyInfo[] objPropertiesArray = objType.GetProperties();

foreach (PropertyInfo objProperty in objPropertiesArray)
{

Control control = FindControl(container, objProperty.Name);
if (control == null) continue;
if (control is DateTimePicker)
{
DateTimePicker dateTimePicker = (DateTimePicker)control;
objProperty.SetValue(obj, Convert.ChangeType(dateTimePicker.Value, objProperty.PropertyType), null);

}
else
{
Type controlType = control.GetType();
PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

bool success = false;
success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));

if (!success)
success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

if (!success)
success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

if (!success)
success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedValue", typeof(String));
}
}
}

private static bool FindAndGetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
{
// 在整个控件属性中进行迭代
foreach (PropertyInfo controlProperty in controlPropertiesArray)
{
// 检查匹配的名称和类型
if (controlProperty.Name == "Text" && controlProperty.PropertyType == typeof(String))
{
// 将控件的属性设置为
// 业务对象属性值
try
{
objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
return true;
}
catch
{
// 无法将来自窗体控件
// 的数据转换为
// objProperty.PropertyType
return false;
}
}
}
return true;
}

}
}

//使用方法:
//业务对象:
public class Model
{
public Model()
{
}

private string test1;
private DateTime test2;
private string test3;

public string Test1
{
set { test1 = value; }
get { return test1; }
}

public DateTime Test2
{
set { test2 = value; }
get { return test2; }
}

public string Test3
{
set { test3 = value; }
get { return test3; }
}
}

在一个Winform中,放两个TextBox控件,一个DateTimePicker控件,一个Panel控件,分别命名位Test1、Test2、Test3,其中把Text3控件放在Panel1中。
将业务对象绑定到窗体:
Model model = new Model();
model.Test1 = "Hello,World!";
model.Test2 = DateTime.Now.AddMonths(-2);
model.Test3 = "Nice to meet u!";
FormBinding.BindObjectToControls(model, this);

将窗体绑定到业务对象:
Model model = new Model();
FormBinding.BindControlsToObject(model, this);
MessageBox.Show(model.Test1 + " " + model.Test2.ToShortDateString() + " " + model.Test3);

分享到:
评论

相关推荐

    通用Winform模板,winform实例大全,C#

    本系统使用winform的绑定机制应用以上模板及对应数据表(视图)实现动态代码生成后续需要做的工作就是应用winform开发自带的数据源方法或者devexpress的datalayoutcontrol方法来拖拽对应的控件和展示数据的gridcontrol...

    通用Winform模板_C#_winform窗体生成_体检系统_winform_lead34w

    本系统使用winform的绑定机制应用以上模板及对应数据表(视图)实现动态代码生成后续需要做的工作就是应用winform开发自带的数据源方法或者devexpress的datalayoutcontrol方法来拖拽对应的控件和展示数据的gridcontrol...

    C# winform 实现按钮固定到菜单栏以及右键菜单

    C# winform 实现按钮固定到菜单栏以及右键菜单

    Winform开发手册

    WinForm 是 Windows Form 的简称,是基于 .NET Framework 平台的客户端(PC软件)开发技术,一般使用 C#...这套 C# WinForm 教程将教会大家如何使用 WinForm 进行界面设计,并绑定对应的事件,开发出一个实用的客户端。

    C#通过DataSet将数据绑定到DataGridView显示

    C#在Winform窗体程序中通过DataSet对象将数据绑定到DataGridView中来显示,DataGridView是用来显示数据库中内容较方便的一个数据显示控件,对C#初学者来说,了解其用法显得很重要,也很实用,通过本程序的代码演示,...

    c# winform动态控件.zip

    通过程序而非手动生成控件 ,并可以为自动生成的控件添加事件等等。资源以自动添加多个Label和Button为例,并为Button绑定单击事件

    winform_datagridview多线程出现红叉解决方案

    winform_datagridview多线程出现红叉解决方案

    c# winform treelistview的使用(treegridview)实例详解

    你可以将TreeListView加入到工具箱中然后在添加到窗体中。 1.你需要添加列 2.你需要添加一个ImageList作为节点图标的容器(你还需要配置TreeListView的SmallImageList属性为ImageList控件的ID) 3.现在可以给控件...

    重写TreeView,实现Shift多个多选和ctrl单个多选

    重写WinForm控件中的TreeView控件,实现了TreeView多选,里面有源代码(vs2010开发的)。可以像Windows中那样用Shift多个选择节点,也可以用Ctrl单个多选节点。压缩包中有源码和示例文件夹(TreeView使用文件夹和文件...

    C#编写的一个带树型结构的下拉框控件

    用C#编写的一个下拉框控件,展开后内部可以有树型结构,对应WINFORM程序特别有用.

    winform绑定快捷键的方法

    本文实例讲述了winform绑定快捷键的方法。分享给大家供大家参考。具体分析如下: 第一种:Alt + *(按钮快捷键) 在大家给button、label、menuStrip等控件设置Text属性时在名字后边加&键名就可以了,比如button1.text= ...

    WinForm 实现图片滚动

    在窗体中拖一个Panal控件 //2、定义一个PicBox用来存储图片,picbox的高度、宽度与Panal的高度相同 //3、实现图片从右向左滚动:picbox.left=panal.right-picbox.Width _pb = new PictureBox(); _pb.Height = ...

    跨窗体实时更新(绑定了数据库)

    winform跨窗体实时更新数据运用timer控件来进行读秒刷新 实时更新数据 适用于初学者进行学习开发项目的一个小Demo

    C# winform编程中响应回车键的实现代码

    本文介绍在使用C#进行窗体(WinForm)编程时,如何设置在窗口上按回车键的响应事件,或者说要响应按钮。 在窗体上按回车键,我们可以设置程序触发一些事件。这些事件都要通过窗体的AcceptButton这个属性来进行绑定。...

    WinForm之BindingSource基础操作实例教程

    这是通过将 BindingSource 组件绑定到数据源,然后将窗体上的控件绑定到 BindingSource 组件来完成的。与数据的所有进一步交互(包括导航、排序、筛选和更新)都是通过调用 BindingSource 组件来完成的。 (2)其次...

    C#开发实例大全(基础卷).软件开发技术联盟(带详细书签) PDF 下载

    主要内容有C#开发环境的使用、C#语言基础应用、字符串处理技术、数组和集合的使用、面向对象编程技术、数据结构与算法、Windows窗体基础、特色窗体界面、窗体控制技术、MDI窗体和继承窗体、Windows常用控件的使用、...

    asp.net知识库

    ASP.NET 2.0中使用webpart系列控件 ASP.NET 2.0 中实现跨页提交 新控件、管理外观、布局及其它用户体验 ASP.NET 2.0 缓存技术 (原创) asp.net 2.0中的theme主题覆盖问题 asp.net 2.0中利用app_offline.htm功能 ...

Global site tag (gtag.js) - Google Analytics