Bu makalede propertygrid üzerinde otomatik enum tipi için lokalizasyon yapmanıza yardımcı olacak kodu paylaşacağım.
Aşağıdaki ise bir enum tipi tanımlayalım.
Burada strings dosyamıza enum isimlerimizi bildirip karşılığında ne istediğimizi tanımlayalım.
Sonuç olarak :
Kolay gelsin, umarım yardımcı olabilmişimdir.
public class GlobalEnumConverter : EnumConverter { Dictionary> _lookupTables; /// /// Instantiate a new Enum Converter /// /// Type of the enum to convert public GlobalEnumConverter(Type type) : base(type) { _lookupTables = new Dictionary>(); } /// /// The lookuptable holds the references between the original values and the localized values. /// /// Culture for which the localization pairs must be fetched (or created) ///Dictionary private DictionaryGetLookupTable(CultureInfo culture) { Dictionary result = null; if (culture == null) culture = CultureInfo.CurrentCulture; if (!_lookupTables.TryGetValue(culture, out result)) { result = new Dictionary (); foreach (object value in GetStandardValues()) { string text = ConvertToString(null, culture, value); if (text != null) { result.Add(text, value); } } _lookupTables.Add(culture, result); } return result; } /// /// Convert the localized value to enum-value /// /// /// /// ///public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { Dictionary lookupTable = GetLookupTable(culture); //LookupTable lookupTable = GetLookupTable(culture); object result = null; if (!lookupTable.TryGetValue(value as string, out result)) { result = base.ConvertFrom(context, culture, value); } return result; //return base.ConvertFrom(context, culture, value); } else { return base.ConvertFrom(context, culture, value); } } /// /// Convert the enum value to a localized value /// /// /// /// /// ///public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value != null && destinationType == typeof(string)) { Type type = value.GetType(); string resourceName = string.Format("{0}_{1}", type.Name, value.ToString()); ResourceManager rm = strings.ResourceManager; string result = rm.GetString(resourceName, culture); if (result == null) result = resourceName; return result; } else { return base.ConvertTo(context, culture, value, destinationType); } } }
Aşağıdaki ise bir enum tipi tanımlayalım.
public class GlobalEnumConverter : EnumConverter [TypeConverter(typeof(GlobalEnumConverter))] public enum PollutantUnits : int { MG_L, UG_L, _L }
Burada strings dosyamıza enum isimlerimizi bildirip karşılığında ne istediğimizi tanımlayalım.
Sonuç olarak :
Kolay gelsin, umarım yardımcı olabilmişimdir.