将枚举值与本地化字符串资源相链接

相关: 从枚举属性获取枚举

我希望以最可维护的方式绑定枚举,并将它与关联的本地化字符串值相关联。

如果我把枚举和类放在同一个文件中,我觉得有些安全,但我必须假设有更好的方法。 我也考虑过将enum名称与资源字符串名称相同,但我担心我不能总是在这里强制执行。

using CR = AcmeCorp.Properties.Resources; public enum SourceFilterOption { LastNumberOccurences, LastNumberWeeks, DateRange // if you add to this you must update FilterOptions.GetString } public class FilterOptions { public Dictionary GetEnumWithResourceString() { var dict = new Dictionary(); foreach (SourceFilterOption filter in Enum.GetValues(typeof(SourceFilterOption))) { dict.Add(filter, GetString(filter)); } return dict; } public String GetString(SourceFilterOption option) { switch (option) { case SourceFilterOption.LastNumberOccurences: return CR.LAST_NUMBER_OF_OCCURANCES; case SourceFilterOption.LastNumberWeeks: return CR.LAST_NUMBER_OF_WEEKS; case SourceFilterOption.DateRange: default: return CR.DATE_RANGE; } } } 

您可以将DescriptionAttribute添加到每个枚举值。

 public enum SourceFilterOption { [Description("LAST_NUMBER_OF_OCCURANCES")] LastNumberOccurences, ... } 

在需要时拉出描述(资源键)。

 FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); } 

http://geekswithblogs.net/paulwhitblog/archive/2008/03/31/use-the-descriptionattribute-with-an-enum-to-display-status-messages.aspx

编辑:对评论的回应(@Tergiver)。 在我的示例中使用(现有)DescriptionAttribute是为了快速完成工作。 您最好实现自己的自定义属性,而不是使用其目的之外的属性。 像这样的东西:

 [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inheritable = false)] public class EnumResourceKeyAttribute : Attribute { public string ResourceKey { get; set; } } 

如果有人没有正确更新,您可能会立即崩溃。

 public String GetString(SourceFilterOption option) { switch (option) { case SourceFilterOption.LastNumberOccurences: return CR.LAST_NUMBER_OF_OCCURANCES; case SourceFilterOption.LastNumberWeeks: return CR.LAST_NUMBER_OF_WEEKS; case SourceFilterOption.DateRange: return CR.DATE_RANGE; default: throw new Exception("SourceFilterOption " + option + " was not found"); } } 

我通过以下方式映射到资源:1。使用ctor获取2个参数(资源类型及其名称)定义一个StringDescription类

 [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] class StringDescriptionAttribute : Attribute { private string _name; public StringDescriptionAttribute(string name) { _name = name; } public StringDescriptionAttribute(Type resourseType, string name) { _name = new ResourceManager(resourseType).GetString(name); } public string Name { get { return _name; } } } 
  1. 为任一文化创建资源文件(例如WebTexts.resx和Webtexts.ru.resx)。 让我们的颜色是红色,绿色等……

  2. 定义枚举:

    枚举颜色{[StringDescription(typeof(WebTexts),“Red”)] Red = 1,[StringDescription(typeof(WebTexts),“Green”)] Green = 2,[StringDescription(typeof(WebTexts),“Blue”)]蓝色= 3,[StringDescription(“Antracit with mad dark circles”)] AntracitWithMadDarkCircles

    }

  3. 定义通过reflection获取资源描述的静态方法

    public static string GetStringDescription(Enum en){

      var enumValueName = Enum.GetName(en.GetType(),en); FieldInfo fi = en.GetType().GetField(enumValueName); var attr = (StringDescriptionAttribute)fi.GetCustomAttribute(typeof(StringDescriptionAttribute)); return attr != null ? attr.Name : ""; } 
  4. 吃 :

    颜色col; col = Colour.Red; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(“en-US”);

      var ListOfColors = typeof(Colour).GetEnumValues().Cast().Select(p => new { Id = p, Decr = GetStringDescription(p) }).ToList(); foreach (var listentry in ListOfColors) Debug.WriteLine(listentry.Id + " " + listentry.Decr); 

我要在WPF中使用它,这是我实现它的方式

首先,您需要定义一个属性

 public class LocalizedDescriptionAttribute : DescriptionAttribute { private readonly string _resourceKey; private readonly ResourceManager _resource; public LocalizedDescriptionAttribute(string resourceKey, Type resourceType) { _resource = new ResourceManager(resourceType); _resourceKey = resourceKey; } public override string Description { get { string displayName = _resource.GetString(_resourceKey); return string.IsNullOrEmpty(displayName) ? string.Format("[[{0}]]", _resourceKey) : displayName; } } } 

您可以像这样使用该属性

 public enum OrderType { [LocalizedDescription("DineIn", typeof(Properties.Resources))] DineIn = 1, [LocalizedDescription("Takeaway", typeof(Properties.Resources))] Takeaway = 2 } 

然后定义一个转换器

 public class EnumToDescriptionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo language) { var enumValue = value as Enum; return enumValue == null ? DependencyProperty.UnsetValue : enumValue.GetDescriptionFromEnumValue(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language) { return value; } } 

然后在你的XAML中

   

有一种最简单的方法可以根据来自资源文件的文化来获取枚举描述值

我的枚举

  public enum DiagnosisType { [Description("Nothing")] NOTHING = 0, [Description("Advice")] ADVICE = 1, [Description("Prescription")] PRESCRIPTION = 2, [Description("Referral")] REFERRAL = 3 

}

我已经创建了资源文件和密钥与枚举描述值相同

Resoucefile和Enum Key和Value Image,单击以查看资源文件图像

  public static string GetEnumDisplayNameValue(Enum enumvalue) { var name = enumvalue.ToString(); var culture = Thread.CurrentThread.CurrentUICulture; var converted = YourProjectNamespace.Resources.Resource.ResourceManager.GetString(name, culture); return converted; } 

在视图上调用此方法

   

它会将字符串accig返回给您的文化