C# - WPF Markup Extension for enum values

By , 11/5/2015
(0 ratings)
This Snippet provides a markup extension for set der values of an enum as a property value.

Required Namespaces
System
System.Windows.Markup

Usage
<ComboBox ItemsSource="{local:EnumSource HorizontalAlignment}"/>
Translate to VB
/// <summary>
/// Provides a markup extension for set up the members of an enum as an items source.
/// </summary>
public class EnumSource : MarkupExtension
{
    /// <summary>
    /// Creates a new instance of <see cref="EnumSource"/>.
    /// </summary>
    /// <param name="enumType">The type of the enumeration which members should be used.</param>
    /// <exception cref="ArgumentNullException">Is thrown when <paramref name="enumType"/> is <c>null</c>.</exception>
    /// <exception cref="NotSupportedException">Is thrown when <paramref name="enumType"/> is not the type of an enum.</exception>
    public EnumSource(Type enumType)
    {
        if (enumType == null)
        {
            throw new ArgumentNullException(nameof(enumType), $"The {nameof(enumType)} parameter must be the type of an enum.");
        }
        if (!enumType.IsEnum)
        {
            throw new NotSupportedException($"The passed type in the {nameof(enumType)} parameter is not an enum");
        }

        EnumType = enumType;
    }

    /// <summary>
    /// Gets the type of the enum.
    /// </summary>
    public Type EnumType { get; private set; }

    /// <summary>
    /// Gets the member of the <see cref="Enumtype"/> type.
    /// </summary>
    /// <param name="serviceProvider">Is not neccessary in this implementation.</param>
    /// <returns>The members of <see cref="Enumtype"/>.</returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Enum.GetValues(EnumType);
    }
}

Comments

 

Log in, to comment!