再做项目的时候需要用到comboBox来配置对象的属性(属性是一个枚举型), 如果一一用字符匹配的方法进行设置就太累了.而且当修改了enum之后.还必须要重新匹配.所以想到了一个办法. 重载了combobox类。用reflection的技术对其动态的绑定。选择了哪一个combobox的item就可以直接返回该enum值.代码不长可以贴上来.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsApplication1.Controls
{
public partial class EnumComboBox : ComboBox
{
#region Private Field
private Type m_type;
private List<object> m_list;
#endregion
#region Constructor
public EnumComboBox()
{
InitializeComponent();
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.Sorted = false;
m_list = new List<object>();
}
#endregion
#region Public Property
public Type TheType
{
get
{
return m_type;
}
set
{
if (value == null)
{
return;
}
if (value.IsEnum)
{
m_type = value;
this.Items.Clear();
System.Reflection.FieldInfo[] fields = m_type.GetFields();
foreach (System.Reflection.FieldInfo fileInfo in fields)
{
if (fileInfo.FieldType.IsEnum)
{
object obj = m_type.InvokeMember(fileInfo.Name,BindingFlags.GetField,null,null,null);
m_list.Add(obj);
this.Items.Add(obj.ToString());
}
}
this.SelectedIndex = 0;
}
}
}
public object CurrentValue
{
get
{
if (this.SelectedIndex == -1)
{
return -1;
}
else
{
return m_list[this.SelectedIndex];
}
}
}
#endregion
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: Add custom paint code here
// Calling the base class OnPaint
base.OnPaint(pe);
}
}
}
在使用的时候可以如下操作
//....枚举的定义
public enum AA{a,b,c,d}
......
//.....初始化
EnumComboBox commbobox = new EnumComboBox();
combobox.TheType = typeof(AA);
....
//....取值
AA a = (AA)combobox.CurrentValue;
本文介绍了一种通过反射技术实现枚举类型与ComboBox动态绑定的方法,简化了枚举属性配置过程,提高了开发效率。
1671

被折叠的 条评论
为什么被折叠?



