-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEnumerationExtension.cs
92 lines (79 loc) · 3.01 KB
/
EnumerationExtension.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
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Markup;
namespace Sharp.Utils.Wpf
{
/// <summary>
/// A markup extension that gives access to Enum values and descriptions in XAML.
/// </summary>
public class EnumerationExtension : MarkupExtension
{
private readonly Type _enumType;
/// <summary>
/// Creates a new <see cref="EnumerationExtension"/> instance.
/// </summary>
/// <param name="enumType">The type of enum for which to get values.</param>
public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
enumType = Nullable.GetUnderlyingType(enumType) ?? enumType;
if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum.", "enumType");
_enumType = enumType;
}
/// <summary>
/// Gets the type of enum for which to get values.
/// </summary>
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return;
}
}
/// <summary>
/// Provides a list containing an <see cref="EnumerationMember"/> containing the value and description for each item in the enum.
/// </summary>
/// <param name="serviceProvider">A service provider helper that can provide services for the markup extension.</param>
/// <returns>A list of EnumerationMembers</returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember
{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
/// <summary>
/// Represents the value and description for an item in the enum.
/// </summary>
public class EnumerationMember
{
/// <summary>
/// Gets or sets the description of the enum item. This is generally determined from the DescriptionAttribute on the enum member, if present.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the value of the enum item.
/// </summary>
public object Value { get; set; }
}
}
}