Main contents

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t or isn’t widely publicized. Click here for a complete list of Missing .NET entries.


I’m ambivalent towards enums. They are a succinct way of providing a list of choices that don’t change that much. But, I think they are overused, often in situations that don’t lend themselves well to enums. For example, the HttpStatusCode enum in System.Net. It should probably explicitly be a list of constant integers, because that’s the way the status code is thought of to HTTP programmers, well, at least one. Consider the two code snippets below. Which one is more readable?

void ProcessResponse(WebResponse r)
{
    if (r.StatusCode >= HttpStatusCode.BadRequest)
    {
        // handle response
    }
}

void ProcessResponse(WebResponse r)
{
    if (r.StatusCode >= 400)
    {
    // handle request
    }
}

Yeah, yeah: you’re not supposed to use magic numbers, but it’s not like HTTPbis is going to redo all the status codes. It’s a safe bet that the status code with the value 400 will always mean “Bad Request”.

Anyway, Enums are here to stay and we have to deal with them in various ways; displaying them to the user is one way they have to be dealt with. I’ll give a treatment of how to display an enum in WPF in this post. You’ll see that displaying them in all situations is non-trivial.

So, let’s say you want to display a list of the values for your custom enum in a ComboBox in WPF; how do you do it? Well,  you could mess around yourself and test your WPF databinding knowledge, but no one has any patience for that nowadays. Let’s Google it! The goal of most WPF code is to do it all in XAML. So a possible solution to the problem is the following XAML snippet (copied from this post from the WPF SDK blog):

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib"
  SizeToContent="WidthAndHeight"
  Title="Show Enums in a ListBox using Binding">
  <Window.Resources>
    <ObjectDataProvider MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}"
                        x:Key="AlignmentValues">
      <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="HorizontalAlignment" />
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
  </Window.Resources>
  <Border Margin="10" BorderBrush="Aqua"
          BorderThickness="3" Padding="8">
    <StackPanel Width="300">
      <TextBlock>Choose the HorizontalAlignment
                 value of the Button:</TextBlock>
      <ListBox Name="myComboBox" SelectedIndex="0" Margin="8"
               ItemsSource="{Binding Source={StaticResource
                                             AlignmentValues}}"/>
      <Button Content="Click Me!"
              HorizontalAlignment="{Binding ElementName=myComboBox,
                                            Path=SelectedItem}"/>
    </StackPanel>
  </Border>
</Window>

The real magic happens in the bolded text above, the ObjectDataProvider. It calls the GetValues() method on the Enum type. The MethodParameters element contains the actual enum type to display. This is the common sample that you’ll see throughout the web. A couple problems no one seems to address with this solution, though.

The first is the what actually gets shown to the user. For simple one-word values, like the HorizontalAlignment enum used in the XAML sample above (Center, Justify, Left, Right), it’s not a problem — if you’re only coding for the English language. But what about the HttpStatusCode enum? It’ll show up with the Pascal casing BadRequest or RequestedRangeNotSatisfiable rather than “Bad Request” or “Requested Range Not Satisfiable”. That’s acceptable if your audience is a bunch of nerdy programmers (“I actually prefer no spaces, it makes 2.4321% more efficient so I can devote more time to WoW!” Nerd.), but if you’re doing this for real people, you’re going to want a nice grammatically- correct string to show up. You might want even more detail in the string: “Bad Request (400)”, say.

Second, this solution ignores localization. If you just show the name of the enum value, you get whatever language the programmer speaks. That’s fine if you only plan on shipping your product to your country, but what if you are big in Japan? You’re going to want to translate that bad boy to Japanese!

Japan's calling. Are you going to answer?

Japan’s calling. Are you going to answer?

Let’s solve that problem.

Let’s first assume that we own the enum type. We have a web product and a WPF product; we use our custom enum type in both products. We want to display the same thing for the enum values in both places. If that’s the case, we want the display strings to move around with the enum. How are we going to do that? Well, we have extra data that we want to move around with a type, perfect for … Attributes!

The simplest attribute class that will work takes a string that will be displayed in place of the enum value. But we don’t want the simplest class that will work. We want one that will also support localization. Still pretty simple and it looks like this:

[AttributeUsage(AttributeTargets.Field)]
public sealed class DisplayStringAttribute : Attribute
{
   private readonly string value;
   public string Value
   {
      get { return value; }
   }

   public string ResourceKey { get; set; }

   public DisplayStringAttribute(string v)
   {
      this.value = v;
   }

   public DisplayStringAttribute()
   {
   }
}

We can apply this to the values of our custom enum, like so:

public enum MyEnum
{
   [DisplayString("My Value")] 
    Value,
   [DisplayString("This means On")]
    On,
   [DisplayString("Off means not On")]
    Off,
   [DisplayString("The great unknown")]
    Unknown,
   [DisplayString("I ain't got none")]
    None
}

Doesn’t look as pretty as an unadorned enum, but commercial quality code often looks less attractive than you’re typical code snippet on MSDN. If we want to internationalize our app, we can have different display strings for different languages by setting the ResourceKey property instead of the value constructor:

public enum MyEnum
{
   [DisplayString(ResourceKey="MyEnum_Value")] Value,
   [DisplayString(ResourceKey="MyEnum_On")] On,
   [DisplayString(ResourceKey="MyEnum_Off")] Off,
   [DisplayString(ResourceKey="MyEnum_Unknown")] Unknown,
   [DisplayString(ResourceKey="MyEnum_None")] None
}
 
Don’t forget to add the strings to your resx file for each language!
 
So we have our strings established, now we need a class that will read that data, and convert it to something that can be displayed. I’ll solve that problem for WPF specifically, but there is no reason you can’t do it for Winforms or the Web also, dear reader. It’s a good lesson in learning how to support UI frameworks and reflection
 
If you’re designing for WPF, a huge consideration is the ability to express your code in XAML. With my solution below, you’ll be able to declare these enum displayers in XAML; but as you’ll see, it makes the code a little less elegant.
 
Here are the requirements that my EnumDisplayer class must fulfill:
  • read the DisplayStringAttribute values applied to our enum class; or
  • load the resource string based on the ResourceKey in the DisplayStringAttribute; and
  • be expressible in XAML, both declaring one and as a databinding source.

Let’s take care of the third item first, since it will shape the public API more than the other two.

It is an enum’s nature to be static and constant, hence a class that aids in displaying it to the user is also likely to be static. We’ll also be using the EnumDisplayer to convert enum values and as a datasource. Before we can do anything though, we need to know the enum type we’ll be displaying. Ideally, this would mean passing the enum type in the constructor; because of the XAML requirement, however we need a property of type Type. We’ll add a constructor that takes a Type parameter as a convenience for those that like to write everything in code. So our initial public API looks thus:

public class EnumDisplayer : IValueConverter
{
  private Type type;
  private IDictionary displayValues;
  private IDictionary reverseValues;
    
  public EnumDisplayer()
  {
  }

  public EnumDisplayer(Type type)
  {
     this.Type = type;
  }

  public Type Type
  {
     get { return type; }
     set
     {
        if (!value.IsEnum)
           throw new ArgumentException("parameter is not an Enumermated type", "value");
        this.type = value;        
     }
  }

  public ReadOnlyCollection<string> DisplayNames
  {
     get
     {
        this.displayValues =...
        return new List<string>((IEnumerable<string>)displayValues.Values).AsReadOnly();
     }
  }
  
  object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
     return displayValues[value];
  }

  object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
     return reverseValues[value];
  }
}

Pretty straightforward public API: two properties, one being the type to generate strings for, and the other, the strings that we generated. The IValueConverter interface is implemented explicitly. The reverseValues dictionary maps the reverse of displayValues: displayValues goes from enum type to string, reverseValues goes from string to enum. This means that each enum value must have a unique display string; hardly unreasonable, since they have to have a unique name within the enum anyway.

The above public API allows us to declare an EnumDisplayer in XAML like so:

<Application.Resources>
        <sm:EnumDisplayer Type="{x:Type FlickrNet:ContentType}" x:Key="contentTypes">
</Application.Resources>

And use it as a data source and value converter:

<ComboBox ItemsSource="{Binding Source={StaticResource contentTypes},Path=DisplayNames}" 
          SelectedValue="{Binding Path=Batch.Photos/ContentType, 
                          Converter={StaticResource contentTypes}}" />

Well, that’s just awesome!

Let’s go back a bit and expand on that ‘…’ in the code for EnumDisplayer. That’s where all the real work happens. Since I don’t know the type at compile time, I use reflection to generate my two IDictionary instances when the DisplayValues property is first accessed. I also inspect the enum type provided for DisplayString attributes. All that code is below. It’s nothing special: most of it I found on the internet if I didn’t already know how to do it.

public ReadOnlyCollection<string> DisplayNames
{
 get
 {
    Type displayValuesType = typeof(Dictionary<,>)
                                .GetGenericTypeDefinition().MakeGenericType(typeof(string),type);
    this.displayValues = (IDictionary) Activator.CreateInstance(displayValuesType);
       
    this.reverseValues =
       (IDictionary)Activator.CreateInstance(typeof(Dictionary<,>)
                .GetGenericTypeDefinition()
                .MakeGenericType(type, typeof(string)));

    var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
    foreach (var field in fields)
    {
       DisplayStringAttribute[] a = (DisplayStringAttribute[])
                                   field.GetCustomAttributes(typeof(DisplayStringAttribute), false);

       string displayString = GetDisplayStringValue(a);
       object enumValue = field.GetValue(null);

       if (displayString == null)
       {
          displayString = GetBackupDisplayStringValue(enumValue);
       }
       if (displayString != null)
       {
          displayValues.Add(enumValue, displayString);
          reverseValues.Add(displayString, enumValue);
       }
    }
    return new List<string>((IEnumerable<string>)displayValues.Values).AsReadOnly();
 }
}

private string GetDisplayStringValue(DisplayStringAttribute[] a)
{
     if (a == null || a.Length == 0) return null;
     DisplayStringAttribute dsa = a[0];
     if (!string.IsNullOrEmpty(dsa.ResourceKey))
     {
        ResourceManager rm = new ResourceManager(type);
        return rm.GetString(dsa.ResourceKey);
     }
     return dsa.Value;
}

Reflection code is always so ugly. I warned you it wasn’t pretty! See what framework developers have to go through to make code usable? So what’s happening here?

First, I dynamically create the two dictionaries as generic types. That begs the question: “Jason, why didn’t you use generics, wouldn’t that have been way easier? You’re such a pedantic loser!”

Good question. I couldn’t use them because of that third requirement that I imposed upon myself: XAML. There’s no easy way to declare a generic type in XAML, so I couldn’t use them.

Moving along: Next I grab the custom attributes, look for my DisplayStringAttribute and get the value from it in the helper method GetDisplayStringValue(). Notice I prefer the ResourceKey property before the Value property.

Then I add them to the dictionary and the reverseDictionary.

Astute readers should be asking this question by now: what about that call to GetBackupDisplayStringValue?

Right you are, Dear Reader! You’re so smart.

Alright, let’s go way back to the top of the article and address one of my assumptions: I assumed that I owned the enum type. That’s a great assumption to make when you’re coming up with trivial code examples for a blog post, but what about the real world? I got a mortgage! And WoW bills! And a flight to Japan to pay for!

It’s not an assumption that holds up under scrutiny. In fact, the chances you’ll be using an enum you own is probably slimmer than not owning the type. We all know everyone will be using the awesome DisplayStringAttribute once this blog post is published, but what about enums that were created B. DSA. (Before DisplayStringAttribute). Don’t worry, I got you covered.

To do that, and make it accessible in XAML, we need two things: a collection of enum display overrides and a way to tell the XAML parser that children of the EnumDisplayer get added to that collection. Here’s the rest of the implementation.

[ContentProperty("OverriddenDisplayEntries")]
public class EnumDisplayer : IValueConverter
{
   private Type type;
   private IDictionary displayValues;
   private IDictionary reverseValues;
   private List<EnumDisplayEntry> overriddenDisplayEntries;
   
    ...

   private string GetBackupDisplayStringValue(object enumValue)
   {
      if (overriddenDisplayEntries != null && overriddenDisplayEntries.Count > 0)
      {
         EnumDisplayEntry foundEntry = overriddenDisplayEntries.Find(delegate(EnumDisplayEntry entry)
                                          {
                                             object e = Enum.Parse(type, entry.EnumValue);
                                             return enumValue.Equals(e);
                                          });
         if (foundEntry != null)
         {
            if (foundEntry.ExcludeFromDisplay) return null;
            return foundEntry.DisplayString;
            
         }
      }
      return Enum.GetName(type, enumValue);
   }
   
   public List<EnumDisplayEntry> OverriddenDisplayEntries
   {
      get
      {
         if (overriddenDisplayEntries == null)
            overriddenDisplayEntries = new List<EnumDisplayEntry>();
         return overriddenDisplayEntries;
      }
   }
}

public class EnumDisplayEntry
{
   public string EnumValue { get; set; }
   public string DisplayString {  get; set; }
   public bool ExcludeFromDisplay { get; set; }
}

We decorate our EnumDisplayer class with the ContentProperty attribute that tells the XAML parser that anything contained in an EnumDisplayer element gets added to that property. Then we also need the property which is a List<EnumDisplayEntry>. The EnumDisplayEntry is a way to map an enum value to a new display string. The GetBackupDisplayStringValue() method is pretty straightforward: query the list for the given enum value to return the string or not if you want to exclude from being displayed. I suppose I should prefer the overridden value to the one provided in the DisplayStringAttribute but I’m jonesing for Guitar Hero, so I’m going to wrap up.

The above code enables you to provide your own strings for enum values, which we can express in XAML:

<sm:EnumDisplayer Type="{x:Type FlickrNet:ContentType}" x:Key="contentTypes">
    <sm:EnumDisplayEntry EnumValue="Photo" DisplayString="Photo (Default)"/>
    <sm:EnumDisplayEntry EnumValue="Screenshot" DisplayString="Screenshot"/>
    <sm:EnumDisplayEntry EnumValue="Other" DisplayString="Other"/>
</sm:EnumDisplayer>

Admittedly, these aren’t the most imaginative strings for these enum values, but that’s an actual snippet of XAML from an actual app.

There are still some things to address: WinForms and ASP.NET should be supported. Also, what about Flags enums? How should those be handled? Enums are surprising in their difficultly to show in UI properly. With the enum displayer class we have a good starting point for making a non-trivial problem of displaying enum values somewhat easier in XAML.

Tags:
This entry is filed under .NET, Missing .NET. You can follow any responses to this entry through the RSS 2.0 feed. Responses are currently closed, but you can trackback from your own site.

14 Comments to “The Missing .NET #7: Displaying Enums in WPF”

  1. Dew Drop - September 3, 2008 | Alvin Ashcraft's Morning Dew Says:

    3 September 2008 at 0908

    [...] The Missing .NET #7: Displaying Enums in WPF (Jason Kemp) [...]

  2. Ro Says:

    30 September 2008 at 0113

    Great post thankyou… I’ve been tearing my hair out trying to get this to work :)

  3. AC374 Says:

    21 November 2008 at 1710

    It looks like your displayValues and reverseValues dictionaries are created backwards (type to string versus string to type).

    For example, shouldn’t displayValuesType be:

    Type displayValuesType = typeof(Dictionary).GetGenericTypeDefinition().
    MakeGenericType(type, typeof(string));

    I had to swap these to make it work.

  4. jackie Says:

    20 February 2009 at 0334

    ComboBox ItemsSource=”{Binding Source={StaticResource contentTypes},Path=DisplayNames}”
    SelectedValue=”{Binding Path=Batch.Photos/ContentType,
    Converter={StaticResource contentTypes}}” />

    have a look at above codes.What the statement’Batch.Photos/ContentType’means?

  5. WolfMoon Says:

    19 March 2009 at 0438

    Both thumbs up for this solution. That’s exactly what I was looking for. It’s smart, simple and very flexible – true programming gem!

  6. Klaus Says:

    23 April 2009 at 1008

    Excellent stuff. Thank you.

  7. Dan Says:

    6 April 2010 at 1656

    Very nice write-up. I learned a lot. Thanks.
    I had one issue when implementing this. The new XAML GUI dev environments (Blend and the VS designer) choke on the EnumDisplayer class. It looks like they’re trying to be too smart for their own good and how you define displayValues confuses them. They throw a null reference exception when they try to inspect the Convert method.

    Adding the below to the Convert method fixes it:
    if (displayValues == null) return null;

    This instantiation of objects within XAML is all very confusing. Can you recommend a source of a good explanation on how this works?

  8. Dave Says:

    9 April 2010 at 0917

    Fantastic writeup, thank you for sharing this! It has definitely helped me out.

    By the way, shouldn’t no spaces make you 32.33 (repeating, of course)% more efficient?

  9. Chris Says:

    11 June 2010 at 0706

    unfortunatelly this solution is absurdally slow, for even just 100 enum-fueled comboboxes in list. So for me its useless.

  10. Steve C Says:

    6 July 2010 at 2223

    That’s enough to make me use a table instead of an enum.

  11. Nahuel Says:

    12 December 2010 at 1055

    Excellent article! Its what I was looking for, And I was not expecting to laugh when reading it, but that is what happend. You should write a book, i would buy it because im sure it wont be boreing.
    (Sory for my english, im from Argentina)

  12. Linus Says:

    18 January 2011 at 0150

    Hi, I have got an error in the DisplayNames property on line:
    displayValues.Add(enumValue, displayString);

    it says the enumValues is not of type “System.String” and cannot be used in this generic collection.

  13. Soarez Says:

    22 January 2011 at 0611

    Creating objects with the activator is very costly, I don’t see why do you have to use reflection to create generic dictionaries where simple non-generic hashtables would suffice. Caching the result of DisplayNames property might also speed it up.

  14. Steve C Says:

    6 July 2011 at 2240

    Linus, read AC374′s note. You have to swap a bit of code to make it work.