Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Разработка Windows Forms > PropertyGrid и CultureInfo


Автор: IEZ 20.9.2007, 16:29
Приветствую Всех!
Есть propertygrid к которому я цепляю класс, одно из свойств которого выглядит так:

Код

class Culture
    {
        private CultureInfo culture;
 
        
        [DisplayName("Наименование")]
        [Category("Культура")]
        [Description("Поле выбора культуры")]
        [TypeConverter(typeof(CultureTypeConverter))]
        public CultureInfo Language
        {
            get { return culture; }
            set { culture = value; }
        }
    }



Конвертер выглядит так:

Код

class CultureTypeConverter : CultureInfoConverter
    {
        CultureInfo[] cultures = null;

        public CultureTypeConverter()
        {
            cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            Array.Sort(cultures, new CultureComparer());
        }

        public class CultureComparer : IComparer
        {
            #region IComparer Members

            public int Compare(object x, object y)
            {
                if (x is CultureInfo && y is CultureInfo)
                {

                    CultureInfo c1 = (CultureInfo)x;
                    CultureInfo c2 = (CultureInfo)y;
                    return c1.DisplayName.CompareTo(c2.DisplayName);
                }
                else
                {
                    throw new ArgumentException("wrong type for CultureComparer");
                }
            }

            #endregion
        }

        /// <summary>
        /// Будем предоставлять выбор из списка
        /// </summary>
        public override bool GetStandardValuesSupported(
           ITypeDescriptorContext context)
        {
            return true;
        }

        /// <summary>
        /// ... и только из списка
        /// </summary>
        public override bool GetStandardValuesExclusive(
           ITypeDescriptorContext context)
        {
            // false - можно вводить вручную
            // true - только выбор из списка
            return true;
        }

        /// <summary>
        /// А вот и список
        /// </summary>
        public override StandardValuesCollection GetStandardValues(
           ITypeDescriptorContext context)
        {
            // возвращаем список строк из настроек программы
            // (базы данных, интернет и т.д.)
            return new StandardValuesCollection(cultures);
        }
    }




Все работает, в свойстве открывается список культур, но только в нем отображается CultureInfo.DisplayName,
а мне нужно, чтобы выводился список состоящий из CultureInfo.NativeName.
Как это можно сделать?
Спасибо.

Автор: tol05 20.9.2007, 19:15
не получится. Открой CultureInfoConverter рефлектором и увидишь, что ConvertTo() имеет такой код
Код

...
 if (destinationType == typeof(string))
    {
        string displayName;
        CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
        if ((culture != null) && culture.Equals(CultureInfo.InvariantCulture))
        {
            Thread.CurrentThread.CurrentUICulture = culture;
        }
        try
        {
            if ((value == null) || (value == CultureInfo.InvariantCulture))
            {
                return this.DefaultCultureString;
            }
            displayName = ((CultureInfo) value).DisplayName;
        }
        finally
        {
            Thread.CurrentThread.CurrentUICulture = currentUICulture;
        }
        return displayName;

...

значит будет этот конвертер будет возвращать displayName всегда.
Выход - переопредели и метод ConvertTo().

P.S. А также ConvertFrom() к нему в пару smile

Автор: IEZ 21.9.2007, 14:14
Цитата(tol05 @  20.9.2007,  19:15 Найти цитируемый пост)
Открой CultureInfoConverter

А где файлец лежит? Чего-то одноименное я не нашел.

Автор: tol05 21.9.2007, 14:18
Цитата(IEZ @  21.9.2007,  14:14 Найти цитируемый пост)
А где файлец лежит? Чего-то одноименное я не нашел

"файлец" - это сборка, содержащая класс CultureInfoConverter, от которого ты наследуешь свой конвертер
называется  эта сборка system.dll и лежит она в гаке.

Ты можешь открыть ее рефлектором и найти в ней класс CultureInfoConverter?

Полное имя класса System.ComponentModel.CultureInfoConverter

Автор: IEZ 21.9.2007, 14:46
tol05,  Чего-то не совсем получается переопределить
Код

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            return base.ConvertTo(context, culture, value, destinationType);
         }

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

Сделал так:
Код

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            return ((CultureInfo)value).NativeName;
        }

Чего-то показывает, но вылетает на ConvertFrom и затем и на ConvertTo.

Совсем затупил.

Автор: IEZ 21.9.2007, 16:30
tol05, Спасибо большое разобрался.
Последний вопрос: можно ли получить список культур с наименованиями на конкретном языке?
Если да то как?

Автор: tol05 21.9.2007, 22:40
нет, ИМХО нельзя. 
CultureInfo - это ведь не словарь, чтобы хранить свое название на всех языках мира.
Тебе сегодня нужно, чтобы все CultureInfo вывели свои имена на венгерском, завтра - на корейском, а я лично давно хотел их  почитать на суахили  smile 

Как я знаю любой из CultureInfo может "расписаться" на трех языках:
- на своем родном (CultureInfo.NativeName). Было б странно, если б он не знал как себя на языке своей культуры величать.
- на английском (CultureInfo.EnglishName). А куда ж без него, кормильца-то?
- на языке локализации FW (CultureInfo.DisplayName). Вот что про это свойство написано:
Цитата

Property Value
The culture name in the format "<languagefull> (<country/regionfull>)" in the language of the localized version of .NET Framework, where <languagefull> is the full name of the language and <country/regionfull> is the full name of the country/region. 
Remarks
For example, if the .NET Framework English version is installed, the DisplayName property for the en-US (English-United States) culture returns "English (United States)". If the .NET Framework Spanish version is installed, regardless of the language that the system is set to display, the culture name is displayed in Spanish; therefore, the DisplayName property for the en-US culture returns "Ingles (Estados Unidos)".

If a custom culture is created by means of the CultureAndRegionInfoBuilder class, the DisplayName property is initialized to the value of the NativeName property.


написано http://msdn2.microsoft.com/en-us/library/system.globalization.cultureinfo.displayname.aspx 
smile

Автор: IEZ 21.9.2007, 23:08
Спасибо. smile 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)