How to use Enum as an ItemsSource using a MarkupExtension.

There are a lot of different ways to use an Enum as a data source for some list, like a ComboBox. I’m going to demonstrate how to create a MarkupExtension that will make your life a lot easier in all your projects. To create a markup extension, create a class that derives from MarkupExtension and overrides ProvideValue(IServiceProvider). Next, add a constructor that takes a System.Type as a parameter, and a property called EnumType to store the type information.

namespace MarkupExtensionDemo.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Markup;
    
    [MarkupExtensionReturnType(typeof(System.Object[]))]
    internal class EnumExtension : MarkupExtension
    {
        public EnumExtension() {
        }

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

        [ConstructorArgument("enumType")]
        public Type EnumType {
            get;
            set;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
 	        if (EnumType == null) {
                throw new System.ArgumentException("The enumeration's type is not set.");
            }

            return Enum.GetValues(EnumType);
        }
    }
}

The real work is done in the ProvideValue(IServiceProvider) method, which actually returns the collection of enumeration values. Now, in our Xaml, we can specify an Enum as an ItemsSource very easily. Let’s say we have the following Enum.

namespace MarkupExtensionDemo
{
    public enum Priority
    {
        Low,
        Medium,
        High
    }
}

We can use it in our Xaml like this.

<UserControl 
             x:Class="MarkupExtensionDemo.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:Extensions="clr-namespace:MarkupExtensionDemo.Extensions"
             xmlns:local="clr-namespace:MarkupExtensionDemo">

    <ComboBox ItemsSource="{Extensions:Enum local:Priority}" />

</UserControl>

It’s important to note that you need to include your namespaces so the types can be resolved. When the markup extension is reached, it executes the ProvideValue(IServiceProvider) method and returns the array of enumeration values to use as the items source.

Leave a Comment

Your email address will not be published.