WPF中ComboBox控件绑定键值对操作
wpf中下拉框将键值对作为其数据源的具体操作。本实例以枚举类型以及枚举特性描述字符串生成键值对来进行。
namespace viewc
{
/// <summary>
/// view.xaml 的交互逻辑
/// </summary>
public partial class view : window
{
private enumtype_enumtype= enumtype.b;
public view()
{
initializecomponent();
initialcombox();
}
private void initialcombox()
{
dictionary<enumtype, string> keyvalues = new dictionary<enumtype, string>();
var pro = typeof(enumtype).getfields();//字段值
for (int i = 0; i < pro.count(); i++)
{
if (pro[i].fieldtype.isenum)//枚举类型
{
var descrips = (descriptionattribute[])pro[i].getcustomattributes(typeof(descriptionattribute), false);//特性描述
if (descrips.length < 0) continue;
var key = (enumtype)typeof(enumtype).invokemember(pro[i].name, system.reflection.bindingflags.getfield, null, null, null);//根据枚举名称得到相应枚举值
keyvalues.add(key, descrips[0].description);
}
}
cmbcontroltype.itemssource = keyvalues;
cmbcontroltype.displaymemberpath = "value";
cmbcontroltype.selectedvaluepath = "key";
}
private void window_loaded(object sender, routedeventargs e)
{
//this.cmbcontroltype.selectedvalue = _controlsteptype;//直接赋值selectvalue属性不会触发selectchanged事件
this.cmbcontroltype.selectedindex = 0;
}
private void cmbcontroltype_selectionchanged(object sender, selectionchangedeventargs e)
{
var controltype = (enumtype)this.cmbcontroltype.selectedvalue;
//dosomething
messagebox.show(controltype .tostring());
}
}
public enum enumtype
{
/// <summary>
/// aa
/// </summary>
[description("aa")]
a,
/// <summary>
/// bb
/// </summary>
[description("bb")]
b,
/// <summary>
/// cc
/// </summary>
[description("cc")]
c,
}
}