-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnumDescriptionTypeConverter.cs
51 lines (47 loc) · 2.08 KB
/
EnumDescriptionTypeConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
namespace BindingEnums
{
public class EnumDescriptionTypeConverter : EnumConverter
{
public EnumDescriptionTypeConverter(Type type)
: base(type)
{}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
if (value != null)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
//Reflect into the value's type to get the display attributes.
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DisplayAttribute displayAttribute = fieldInfo?
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.SingleOrDefault();
if (displayAttribute == null)
{
return value.ToString();
}
else
{
//Look up the localized string.
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
string name = resourceManager.GetString(displayAttribute.Name);
return string.IsNullOrWhiteSpace(name) ? displayAttribute.Name : name;
}
}
}
return string.Empty;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}