【问题标题】:Display enum in ComboBox with spaces在带有空格的 ComboBox 中显示枚举
【发布时间】:2010-11-09 06:38:40
【问题描述】:

我有一个枚举,例如:

enum MyEnum
{
My_Value_1,
My_Value_2
}

与:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

但现在我的问题是:如何将“_”替换为“”,使其变为 带有空格而不是下划线的项目?而且数据绑定对象仍然 作品

【问题讨论】:

标签: c#


【解决方案1】:

如果您可以访问 Framework 3.5,您可以执行以下操作:

Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(e=> new
                {
                    Value = e,
                    Text = e.ToString().Replace("_", " ")
                });

这将返回一个匿名类型的 IEnumerable,它包含一个 Value 属性,即枚举类型本身,以及一个 Text 属性,它将包含枚举数的字符串表示,下划线替换为空格。

Value 属性的目的是您可以准确地知道在组合中选择了哪个枚举数,而不必取回下划线并解析字符串。

【讨论】:

  • 我已经做了,但现在的问题是 cboSurveyRemarksType.SelectedItem ....我无法设置所选项目.....怎么做
  • 用空格替换 _ 后 cboBLVisual.SelectedItem = Enum.Value;为什么不工作?
  • SelectedItem 不起作用,因为它引用了我们使用查询创建的匿名类型(具有值/文本属性的类型),您必须使用 SelectedValue 属性 cboBLVisual.SelectedValue = Enum。价值
  • cboBLVisual.SelectedValue = Enum.Value 此行显示错误...消息低于无法在具有空 ValueMember 的 ListControl 中设置 SelectedValue。
  • 您将如何使用它?我想您会将此 LINQ 语句的结果设置为 DataSource 属性。然后将ValueMember 属性设置为"Text" 吗?你将如何取回枚举值?我不确定您如何将 SelectedItem 转换回由 LINQ 语句产生的匿名类型。
【解决方案2】:

如果您能够修改定义枚举的代码,从而可以在不修改实际枚举值的情况下为值添加属性,那么您可以使用此扩展方法。

/// <summary>
/// Retrieve the description of the enum, e.g.
/// [Description("Bright Pink")]
/// BrightPink = 2,
/// </summary>
/// <param name="value"></param>
/// <returns>The friendly description of the enum.</returns>
public static string GetDescription(this Enum value)
{
  Type type = value.GetType();

  MemberInfo[] memInfo = type.GetMember(value.ToString());

  if (memInfo != null && memInfo.Length > 0)
  {
    object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attrs != null && attrs.Length > 0)
    {
      return ((DescriptionAttribute)attrs[0]).Description;
    }
  }

  return value.ToString();
}

【讨论】:

    【解决方案3】:

    试试这个...

    comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
                               .Cast<MyEnum>()
                               .Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
                               .ToList();
    comboBox1.DisplayMember = "Description";
    comboBox1.ValueMember = "Value";
    

    ...虽然,我更倾向于使用“描述”属性(根据 Steve Crane 的回答)

    【讨论】:

      【解决方案4】:

      手动填充组合框并对枚举进行字符串替换。

      这正是您需要做的:

      comboBox1.Items.Clear();
      MyEnum[] e = (MyEnum[])(Enum.GetValues(typeof(MyEnum)));
      for (int i = 0; i < e.Length; i++)
      {
          comboBox1.Items.Add(e[i].ToString().Replace("_", " "));
      }
      

      要设置组合框的选定项,请执行以下操作:

      comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");
      

      【讨论】:

      • 我的枚举有 10 个值,如何手动设置它们......你知道动态设置吗
      • 循环遍历枚举中的所有值。见:stackoverflow.com/questions/972307
      • 我已经编辑了我的答案,以准确包含您需要做的事情。
      • 我已经更新了我的答案,向您展示如何设置所选项目。
      【解决方案5】:

      如果您使用的是 .NET 3.5,则可以添加此扩展类:

      public static class EnumExtensions {
      
          public static List<string> GetFriendlyNames(this Enum enm) {
              List<string> result = new List<string>();
              result.AddRange(Enum.GetNames(enm.GetType()).Select(s => s.ToFriendlyName()));
              return result;
          }
      
          public static string GetFriendlyName(this Enum enm) {
              return Enum.GetName(enm.GetType(), enm).ToFriendlyName();
          }
      
          private static string ToFriendlyName(this string orig) {
              return orig.Replace("_", " ");
          }
      }
      

      然后设置您的组合框,您只需:

      MyEnum val = MyEnum.My_Value_1;
      comboBox1.DataSource = val.GetFriendlyNames();
      comboBox1.SelectedItem = val.GetFriendlyName();
      

      这应该适用于任何枚举。您必须确保包含 EnumExtensions 类的命名空间的 using 语句。

      【讨论】:

        【解决方案6】:

        我认为将内部枚举名称映射到用户空间并不是一个好主意。如果你重构你的枚举值怎么办?所以我建议你看看这个article (Localizing .NET Enums)。使用本文介绍的技术,您不仅可以将“_”替换为空格,还可以为不同的语言(使用资源)制作不同的枚举表示。

        【讨论】:

        • 动态是什么意思?您只需将所有值绑定到组合框中。我提到的文章完全符合这一点。
        【解决方案7】:

        我喜欢 Kelsey 的回答,尽管我会使用除 'e' 之外的另一个变量,例如 'en',因此该答案可以在事件处理程序中使用,并且不那么麻烦;事件处理程序中的“e”往往是 EventArgs 参数。 至于 LINQ 和 IEnumerable 方法,在我看来,使用 .NET 3.5 适应非 WPF ComboBoxes 似乎更加复杂和困难

        【讨论】:

          猜你喜欢
          • 2012-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-24
          • 1970-01-01
          • 2012-07-29
          • 2010-12-05
          • 1970-01-01
          相关资源
          最近更新 更多