poniedziałek, 17 czerwca 2013

Generic Int to Enum Converter - WPF example

I'm proud to present how to convert integer value to any enum you ever would like to :-)
Below example ilustrates use it e.g in WPF application.
We need to create Converter class as showed below. And of course create some enums
    public class GenericIntToEnumConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (((Type)parameter).IsEnum && value is int)
            {
                return Enum.GetName((Type)parameter, value);
            }
            return null;
        }



        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (int)value;
        }
    }



    public enum ExampleEnum
    {
        First = 1,
        Second =2,
        Third =3
    }
Usage is very easy we just pass as the parametr the destination enum: