枚举作为CheckBoxList的数据源

时间:2014-07-24 06:30:16

标签: c# wpf

我创建了enum对象,如下所示

public enum Status
{
   Active,
   Inactive,
   Deleted
}

我想将那些enum绑定到CheckBoxList。

我试过了,

chkStatus.DataSource = Status;
chkStatus.DataBind();

有可能吗?如果是这样,怎么办?

3 个答案:

答案 0 :(得分:3)

尝试:

    public enum Status
    {
       Active = 0,
       Inactive = 1,
       Deleted = 2
    }

并绑定CheckBoxList

checkboxID.DataSource = Enum.GetNames(typeof(Status));
checkboxID.DataBind();

答案 1 :(得分:2)

考虑这个枚举:

public enum Status
{
   Active=1,
   Inactive=2,
   Deleted=3
}

然后你可以这样做:

yourCheckBoxList.DataSource= Enum
        .GetValues(typeof(Status))
        .Cast<Status>()
        .Select (s =>new KeyValuePair<int,string>((int)s,s.ToString()))
        .ToList();

yourCheckBoxList.DataValueField="Key";
yourCheckBoxList.DataTextField="Value";
yourCheckBoxList.DataBind();

答案 2 :(得分:0)

Dictionary<Status, string> dict = new Dictionary<Status, string>();
dct.Add(Status.Active, "Active");
dct.Add(Status.Inactive, "Inactive");
dct.Add(Status.Deleted, "Deleted");

BindingSource src = new BindingSource();
src.Datasource = dict;

((ListBox)YourCheckList).ValueMember = "key";
((ListBox)YourCheckList).DisplayMember = "value;
((ListBox)YourCheckList).Datasource = src;
((ListBox)YourCheckList).DataBind();

希望此代码段能为您提供帮助。