Linking enum value with localized string resource

前端 未结 5 584
终归单人心
终归单人心 2021-01-02 18:15

Related: Get enum from enum attribute

I want the most maintainable way of binding an enumeration and it\'s associated localized string values to something.

5条回答
  •  旧巷少年郎
    2021-01-02 18:40

    I've to use it in WPF here is how I achieve it

    First of all you need to define an attribute

    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;
            }
        }
    }
    

    You can use that attribute like this

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

    Then Define a converter like

    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;
        }
    }
    

    Then in your XAML

    
    
    
    

提交回复
热议问题