Localized boolean typeconverter

 

J'utilise dans mes applications winforms le controle PropertyGrid que je trouve très pratique pour exposer dans une interface utilisateur les propriétés d'un objet, lorsqu'une propriété est de type boolean ce controle affiche une combobox avec 2 valeurs non localisées "True" ou "False", pas vraiment pratique pour des utilisateurs français, voici une classe qui permet d'afficher ces valeurs en français ou autre langue en complétant un peu.

.
   public class LocalizedBooleanTypeConverter : TypeConverter
   {
 
      /// <summary>
      /// Converts the given value object to the specified type, using the specified context and culture information.
      /// </summary>
      /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
      /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/>. If null is passed, the current culture is assumed.</param>
      /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
      /// <param name="destinationType">The <see cref="T:System.Type"/> to convert the <paramref name="value"/> parameter to.</param>
      /// <returns>
      /// An <see cref="T:System.Object"/> that represents the converted value.
      /// </returns>
      /// <exception cref="T:System.ArgumentNullException">The <paramref name="destinationType"/> parameter is null. </exception>
      /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
      public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
      {
         if (destinationType == typeof(string) && value is bool)
         {
            if (culture.TwoLetterISOLanguageName == "fr")
            {
               return (bool)value ? "Vrai" : "Faux";
            }
         }
         return base.ConvertTo(context, culture, value, destinationType);
      }
 
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
            if (culture.TwoLetterISOLanguageName == "fr")
            {
               return value.Equals("Vrai") ? true : false;
            }
            else
            {
               return value.Equals("True") ? true : false;
            }
            }
            else if (value is bool)
            {
                return (bool)value;
            }
            return base.ConvertFrom(context, culture, value);
        }
 
        /// <summary>
        /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="sourceType">A <see cref="T:System.Type"/> that represents the type you want to convert from.</param>
        /// <returns>
        /// true if this converter can perform the conversion; otherwise, false.
        /// </returns>
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            else if (sourceType == typeof(bool))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }
 
        /// <summary>
        /// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context that can be used to extract additional information about the environment from which this converter is invoked. This parameter or properties of this parameter can be null.</param>
        /// <returns>
        /// A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> that holds a standard set of valid values, or null if the data type does not support a standard set of values.
        /// </returns>
        public override StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
        {
         List<String> list = new List<String>();
         string language = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
         System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(language);
         if (ci.TwoLetterISOLanguageName == "fr")
         {
            list.Add("Vrai");
            list.Add("Faux");
         }
         else
         {
            list.Add("True");
            list.Add("False");
         }
            StandardValuesCollection svc = new StandardValuesCollection(list);
            return svc;
        }
 
        /// <summary>
        /// Returns whether the collection of standard values returned from <see cref="M:System.ComponentModel.TypeConverter.GetStandardValues"/> is an exclusive list of possible values, using the specified context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <returns>
        /// true if the <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> returned from <see cref="M:System.ComponentModel.TypeConverter.GetStandardValues"/> is an exhaustive list of possible values; false if other values are possible.
        /// </returns>
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }
 
      /// <summary>
      /// Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.
      /// </summary>
      /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
      /// <returns>
      /// true if <see cref="M:System.ComponentModel.TypeConverter.GetStandardValues"/> should be called to find a common set of values the object supports; otherwise, false.
      /// </returns>
      public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
      {
         return true;
      }
 
   }

 


Le principe etant d'overrider la methode GetStandardValuesSupported et de retourner "true", indiquer aussi en overridant GetStandardValuesExclusive en retournant "true" pour indiquer qu'il sagit d'une liste finie.


Il faut overrider la methode GetStandardValues pour retourner la liste des valeurs possibles , en l'occurence "Vrai" ou "Faux" en ayant detecté la culture en cours de l'utilisateur via l'objet CultureInfo


Les methodes ConvertTo et ConvertFrom etant la pour affecter ou lire la valeur de la propriété de l'objet Mappé par le controle PropertyGrid


Exemple d'utilisation sur un objet :


.


   public class Product
   {
      public string Code { get; set; }
      public string Description { get; set; }
      [TypeConverter(typeof(LocalizedBooleanTypeConverter))]
      public bool IsEnabled { get; set; }
   }

image


Voici le code source :


1 commentaire:

Kitai a dit…

Merci pour ce snippet qui m'a bien été utile.