Last active
October 30, 2018 11:29
-
-
Save erkantaylan/b0e961c691cea44d02c685915c178dde to your computer and use it in GitHub Desktop.
Show Enum Description on View, Converter and Sample Enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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"/> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public enum ColorTypes | |
| { | |
| [Description("Mavi")] Blue, | |
| [Description("Kırmızı")] Red, | |
| [Description("Yeşil")] Green, | |
| [Description("Sarı")] Yellow | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All credits to https://stackoverflow.com/questions/3985876/wpf-binding-a-listbox-to-an-enum-displaying-the-description-attribute