Enum localization

后端 未结 15 761
慢半拍i
慢半拍i 2020-11-30 17:56

How do you localize enums for a ListBoxFor where multiple options are possible?

For example an enum that contains roles:

pu         


        
15条回答
  •  一生所求
    2020-11-30 18:15

    A version of @eluxen's answer working for certain portable (PCL) libraries (specifically for Profile47) where original solution won't work. Two problems were addressed: DescriptionAttribute is not available in portable libraries, and problem reported by @Jitendra Pancholi with "Could not find any resources" error is solved

    public class LocalizedDescriptionAttribute : Attribute
    {
        private readonly string _resourceKey;
        private readonly Type _resourceType;
        public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
        {
            _resourceType = resourceType;
            _resourceKey = resourceKey;
        }
    
        public string Description
        {
            get
            {
                string displayName = String.Empty;
                ResourceManager resMan = _resourceType.GetProperty(
                    @"ResourceManager", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null) as ResourceManager;
                CultureInfo culture = _resourceType.GetProperty(
                        @"Culture", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null) as CultureInfo;
    
                if (resMan != null)
                {
                    displayName = resMan.GetString(_resourceKey, culture);
                }
    
                var ret = string.IsNullOrEmpty(displayName) ? string.Format("[[{0}]]", _resourceKey) : displayName;
                return ret;
            }
        }
    }
    

    For usage see the original answer. And if you are not encountering any problems, I would still use the original answer because it does not contain workarounds through reflection

提交回复
热议问题