ComboBox 填充枚举类型。

3

我该如何将特定的枚举绑定到一个下拉框中?

public enum EduTypePublicEnum
  {
    [RMSEnumItem("1", "Properties.Resources.SEduAlumn")]
    Alumn,
    [RMSEnumItem("2", "Properties.Resources.SEduProfesor")]
    Profesor,
    [RMSEnumItem("3", "Properties.Resources.SEduAll")]
    All
  }

  public class EduTypePublic : RMSEnum<EduTypePublicEnum> { };

在我的表单中
public EduAvisosForm()
{
     InitializeComponent();

     this.myComboBox.DataSource = Edu.Consts.EduTypePublic.Enums;
     this.myComboBox.DisplayMember = "Alumn";
     this.myComboBox.ValueMember = "Alumn";
}

但是,无论有没有ValueMember,都会出现错误。当我没有ValueMember时,放置这段代码会出错,要求使用ValueMember,如果我放上它,它就不起作用。

"在值成员为空的列表控件中不能定义SelectedValue"

public abstract class RMSEnum<TEnumType>
    {
        protected RMSEnum();

        public static string CodeList { get; }
        public static string[] Codes { get; }
        public static string DescriptionList { get; }
        public static string[] Descriptions { get; }
        public static object[] Enums { get; }

        public static string Code(TEnumType value);
        public static string Description(string code);
        public static string Description(TEnumType value);
        public static TEnumType Enum(string code);
    }

Edu.Consts.EduTypePublic.Enums 是什么? - Sergey Berezovskiy
返回一个对象数组,其中包括[校友,教授,全部]。 - Lucas_Santos
我关注这行代码 this.myComboBox.DataSource = Edu.Consts.EduTypePublic.Enums - T.S.
枚举返回一个对象数组,而在我的例子中是[Alumn(校友),Profesor(教授),All(全部)]。 - Lucas_Santos
1个回答

0

您的数据源项应具有您指定为显示和值成员的属性。例如,字典KeyValuePairs具有名为Key和Value的属性:

 this.myComboBox.DisplayMember = "Value";
 this.myComboBox.ValueMember = "Key";
 this.myComboBox.DataSource = 
      Enum.GetValues(typeof(EduTypePublicEnum))
          .Cast<EduTypePublicEnum>()
          .Select(e => new { 
               Key = e.ToString(), // possibly read localized string
               Value = e
           }).ToList();

首先,你应该在分配数据源之前设置显示成员和值成员 - 这是不正确的。我一直先设置DataSource - T.S.
@T.S. 让我检查一下,也许我忘了什么。 - Sergey Berezovskiy
1
@T.S. 实际上,你应该这样做。如果在设置其他成员之前先设置数据源,那么会不必要地多次调用控件的“刷新”操作。当数据源为空时,设置成员属性不会产生任何效果。 - LarsTech
@LarsTech 我记得有关于首先设置成员的事情! - Sergey Berezovskiy
我很久以前在这里读到过:12个加速Windows窗体应用程序的技巧。第8项。 - LarsTech
1
@SergeyBerezovskiy 好的,知道了这个优化。谢谢。 - T.S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接