TypeConverter не вызывается при привязке данных в формах Xamarin - PullRequest
0 голосов
/ 09 января 2020

Я пытаюсь привязать перечисление к элементу управления Picker и отображать локализованные имена для пользователя. Я использую тот же код, который отлично работает в моем приложении WPF, но по какой-то причине он не работает в формах Xamarin и отображает именованные константы enum вместо локализованных имен. Похоже, что TypeConverter не вызывается. Я проверил, что преобразователь типов работает должным образом: TypeDescriptor.GetConverter(typeof(Country)).ConvertTo(Country.sr, typeof(string)) as string; возвращает локализованное имя.

Вот мой класс преобразователя типов

    public class EnumDescriptionTypeConverter : EnumConverter
    {
        public EnumDescriptionTypeConverter(Type type)
            : base(type)
        {
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                if (value != null)
                {
                    FieldInfo fi = value.GetType().GetField(value.ToString());
                    if (fi != null)
                    {
                        var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        return ((attributes.Length > 0) && (!String.IsNullOrEmpty(attributes[0].Description))) ? attributes[0].Description : value.ToString();
                    }
                }

                return string.Empty;
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }

и мой класс DescriptionAttribute

    public class LocalizedDescriptionAttribute : DescriptionAttribute
    {
        ResourceManager _resourceManager;
        readonly string _resourceKey;

        public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
        {
            _resourceManager = new ResourceManager(resourceType);
            _resourceKey = resourceKey;
        }

        public override string Description
        {
            get
            {
                string description = _resourceManager.GetString(_resourceKey);
                return string.IsNullOrWhiteSpace(description) ? string.Format("[[{0}]]", _resourceKey) : description;
            }
        }
    }

и мое перечисление

    [TypeConverter(typeof(EnumDescriptionTypeConverter))]
    public enum Country
    {
        [LocalizedDescription("sl", typeof(Resource))]
        sl,
        [LocalizedDescription("sr", typeof(Resource))]
        sr,
        [LocalizedDescription("th", typeof(Resource))]
        th
    }
...