【问题标题】:How to add space to bound enum values?如何为绑定的枚举值添加空间?
【发布时间】:2025-12-23 06:10:06
【问题描述】:

How do I have an enum bound combobox with custom string formatting for enum values?How to set space on Enum 的帖子中展示了如何向枚举值添加描述,以便能够添加空格,这在将组合框绑定到字符串值时可用。我的情况是这个组合框的选定项也绑定到另一个控件。 使用我通过该链接找到的解决方案,我得到的所选项目的值仍然是没有空格的 Enum 的值。

我的枚举如下所示

[TypeConverter(typeof(EnumToStringUsingDescription))]
public enum SCSRequestType {       
   [Description ("Change Request")]
   ChangeRequest = 4,

   [Description("Documentation")]
   Documentation = 9,....
}

我也在使用下面的类型转换器。

public class EnumToStringUsingDescription : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return (sourceType.Equals(typeof(Enum)));
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return (destinationType.Equals(typeof(String)));
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (!destinationType.Equals(typeof(String)))
        {
            throw new ArgumentException("Can only convert to string.", "destinationType");
        }

        if (!value.GetType().BaseType.Equals(typeof(Enum)))
        {
            throw new ArgumentException("Can only convert an instance of enum.", "value");
        }

        string name = value.ToString();
        object[] attrs =
            value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name;
    }
}

我在这里遗漏了什么,我如何强制组合框的选定项目成为枚举值描述的值。我也愿意接受替代品。

【问题讨论】:

    标签: c# wpf data-binding combobox typeconverter


    【解决方案1】:

    我发现的最好方法是在这个post 中。它会创建一个标记扩展,然后您只需绑定到您的组合框。

    【讨论】:

      【解决方案2】:

      或者您可以设置一个扩展程序。在命名空间的顶层创建 public static class Extensions。在那里你创建这个方法:

      public static string getDescription(this SCSRequestType scs)
      {
          switch (scs)
          {
              case SCSRequestType.ChangeRequest:
                  return "Change Request";
              case SCSRequestType.Documentation:
                  return "Documentation";
              default:
                  return null;
          }
      }
      

      最后你调用string description = SCSRequestType.ChangeRequest.getDescription(); 来访问描述。

      【讨论】:

      • 我不确定这是否是正确的轨道,我的其他控件绑定到 xaml 中组合框的选定项。使用此解决方案就像在绑定到所选项目的属性中使用 switch-case 语句,如下所示 'public string SCSRequestTypeSelectedItem(){get; set{ if(_SCSRequestType != value) // 我可以在这里使用 switch-case 来添加空格 }} '.对我来说,这是混乱和重复的。