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

namespace Gestor.Common.Helpers;

public class EnumBindingSourceExtension : MarkupExtension
{
	private Type _enumType;

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

	public EnumBindingSourceExtension()
	{
	}

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

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