summaryrefslogtreecommitdiff
path: root/Codemerx/Gestor.Common/Gestor.Common.Helpers/EnumBindingSourceExtension.cs
blob: 7ce699ec0da7421b7a230747dd7e82317f7e37cf (plain)
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
using System;
using System.Windows.Markup;

namespace Gestor.Common.Helpers
{
	public class EnumBindingSourceExtension : MarkupExtension
	{
		private Type _enumType;

		public Type EnumType
		{
			get
			{
				return this._enumType;
			}
			set
			{
				if (value == this._enumType)
				{
					return;
				}
				if (null != value)
				{
					if (!(Nullable.GetUnderlyingType(value) ?? value).IsEnum)
					{
						throw new ArgumentException("Type must be for an Enum.");
					}
				}
				this._enumType = value;
			}
		}

		public EnumBindingSourceExtension()
		{
		}

		public EnumBindingSourceExtension(Type enumType)
		{
			this.EnumType = enumType;
		}

		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			if (null == this._enumType)
			{
				throw new InvalidOperationException("The EnumType must be specified.");
			}
			Type underlyingType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
			Array values = Enum.GetValues(underlyingType);
			if (underlyingType == this._enumType)
			{
				return values;
			}
			Array arrays = Array.CreateInstance(underlyingType, values.Length + 1);
			values.CopyTo(arrays, 1);
			return arrays;
		}
	}
}