Skip to content

Instantly share code, notes, and snippets.

@erkantaylan
Last active October 30, 2018 11:29
Show Gist options
  • Select an option

  • Save erkantaylan/b0e961c691cea44d02c685915c178dde to your computer and use it in GitHub Desktop.

Select an option

Save erkantaylan/b0e961c691cea44d02c685915c178dde to your computer and use it in GitHub Desktop.
Show Enum Description on View, Converter and Sample Enum
<ObjectDataProvider x:Key="ColorsEnumDataProvider"
MethodName="GetValues"
ObjectType="{x:Type system:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="models:ColorTypes" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<converters:EnumDescriptionConverter x:Key="EnumDescriptionConverter"/>
public enum ColorTypes
{
[Description("Mavi")] Blue,
[Description("Kırmızı")] Red,
[Description("Yeşil")] Green,
[Description("Sarı")] Yellow
}
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Windows.Data;
public class EnumDescriptionConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Enum myEnum))
{
return null;
}
string description = GetEnumDescription(myEnum);
return description;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Empty;
}
private string GetEnumDescription(Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
{
return enumObj.ToString();
}
DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
@erkantaylan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment