Enum GetValues markup extension

8 Jul

There are plenty of posts dealing with binding an ItemsControl to an Enum’s values. Beatriz Costa demonstrates how to accomplish this purely in xaml. We end up with something like the following.

<ObjectDataProvider MethodName="GetValues" 
    ObjectType="{x:Type s:Enum}" x:Key="EnumValues">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="src:DevicePointFormat" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>        

   

This feels a little on the verbose side to me. The Enum type itself (DevicePointFormat) is in the xaml so each time we need another Enum type’s values we will need to essentially duplicate the xaml snippet. Sounds like we could use a markup extension.

public class EnumValuesExtension : MarkupExtension
{
    private readonly Type _enumType;
 
    public EnumValuesExtension(Type enumType)
    {
        if (enumType == null)
            throw new ArgumentNullException("enumType");
        if (!enumType.IsEnum)
            throw new ArgumentException("Argument enumType must derive from type Enum.");
 
        _enumType = enumType;
    }
 
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Enum.GetValues(_enumType);
    }
}

 

With the EnumValuesExtension we no longer need to create an ObjectDataProvider, we simply hand the Enum type we’re interested in to the markup extension and bind to the returned values.

<ComboBox ItemsSource="{Binding Source={c:EnumValues {x:Type src:DevicePointFormat}}} />

 

Not rocket science but you might find it useful.

2 Responses to “Enum GetValues markup extension”

Trackbacks/Pingbacks

  1. Localize Enum Values « Summergoat’s Weblog - July 16, 2008

    […] 16, 2008 by summergoat In a previous post I created a markup extension which could be used to bind an Enum’s values to an ItemsControl. Now […]

  2. Remmrit Bookmarking - August 3, 2008

    Bookmarks…

    Remmrit.com user has just tagged your post as !…

Leave a comment