/
EnumDescriptionConverter.cs
93 lines (83 loc) · 2.8 KB
/
EnumDescriptionConverter.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//source: https://www.codeproject.com/Articles/22717/Using-PropertyGrid
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
namespace VE3NEA.HamCockpit.PluginHelpers
{
/// <summary>
/// Provides a type converter that allows editing properties of <c>enum</c> type
/// in the Plugin Settings dialog.
/// </summary>
/// <remarks>
/// If a property of <c>enum</c> type in the <c>Settings</c> object of a plugin needs to be edited
/// in the Plugin Settings dialog, use this class as a <c>TypeConverter</c> attribute for that property.
/// With this attribute, the editor shows the descriptions of <c>enum</c> values instead of the values themselves.
/// </remarks>
/// <example>
/// Enum values with descriptions:
/// <code>
/// enum InputType {
/// [Description("Left Channel")]
/// LeftChannel,
///
/// [Description("Right Channel")]
/// RightChannel,
///
/// [Description("Diversity (stereo)")]
/// DiversityStereo
///}
/// </code></example>
/// <example>
/// TypeConverter attribute:
/// <code>
/// [TypeConverter(typeof(EnumDescriptionConverter))]
/// public InputType InputType { get; set; }
/// </code></example>
public class EnumDescriptionConverter : EnumConverter
{
private Type _enumType;
/// <exclude />
public EnumDescriptionConverter(Type type) : base(type)
{
_enumType = type;
}
/// <exclude />
public override bool CanConvertTo(ITypeDescriptorContext context, Type destType)
{
return destType == typeof(string);
}
/// <exclude />
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destType)
{
FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, value));
DescriptionAttribute dna =
(DescriptionAttribute)Attribute.GetCustomAttribute(
fi, typeof(DescriptionAttribute));
if (dna != null)
return dna.Description;
else
return value.ToString();
}
/// <exclude />
public override bool CanConvertFrom(ITypeDescriptorContext context, Type srcType)
{
return srcType == typeof(string);
}
/// <exclude />
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
foreach (FieldInfo fi in _enumType.GetFields())
{
DescriptionAttribute dna =
(DescriptionAttribute)Attribute.GetCustomAttribute(
fi, typeof(DescriptionAttribute));
if ((dna != null) && ((string)value == dna.Description))
return Enum.Parse(_enumType, fi.Name);
}
return Enum.Parse(_enumType, (string)value);
}
}
}