如何将 CheckedListBox 绑定到枚举?
How to bind a CheckedListBox to an enum?
我有一个枚举:
enum Presidents
{
Clinton,
Bush,
Obama,
Trump
}
我也有一个CheckedListBox
。我希望它包含枚举值。我怎样才能做到这一点?
注:一个CheckedListBox
是不是一个CheckBoxList
。请不要参考this问题。
您可以像这样枚举枚举值的名称:
Enum.GetNames(typeof(Presidents));
或通过
的值
Enum.GetValues(typeof(Presidents));
用这个你可以填写 CheckedListBox
的 DataSource
:
checkedListBox1.DataSource = Enum.GetValues(typeof(Presidents));
或者直接填写Items
集合:
checkedListBox1.Items.AddRange(Enum.GetValues(typeof(Presidents));
我建议使用值而不是名称。它们以名称显示,但稍后您可以直接使用它们,如
Presidents firstChecked = (Presidents)checkedListBox1.CheckedItems[0];
无需再次解析它们。
请注意,DataSource
属性 对于此类型不可浏览(在设计器的 属性 window 中可见)。
我有一个枚举:
enum Presidents
{
Clinton,
Bush,
Obama,
Trump
}
我也有一个CheckedListBox
。我希望它包含枚举值。我怎样才能做到这一点?
注:一个CheckedListBox
是不是一个CheckBoxList
。请不要参考this问题。
您可以像这样枚举枚举值的名称:
Enum.GetNames(typeof(Presidents));
或通过
的值Enum.GetValues(typeof(Presidents));
用这个你可以填写 CheckedListBox
的 DataSource
:
checkedListBox1.DataSource = Enum.GetValues(typeof(Presidents));
或者直接填写Items
集合:
checkedListBox1.Items.AddRange(Enum.GetValues(typeof(Presidents));
我建议使用值而不是名称。它们以名称显示,但稍后您可以直接使用它们,如
Presidents firstChecked = (Presidents)checkedListBox1.CheckedItems[0];
无需再次解析它们。
请注意,DataSource
属性 对于此类型不可浏览(在设计器的 属性 window 中可见)。