Andrej Tozon's blog

In the Attic


Binding to Enums

I’ve seen numerous questions regarding data binding to Enums, together with many solutions on how to do it, but the question I’m asking myself is – do I really want to bind anything to an Enum?

I like to think about Enums purely as a coding aid – to help programmer code with some descriptive names instead of messing with pure numeric values. Similar to what constants are for, except Enums provide a set of values for describing a single parameter.

Instead of:

product.Quality = 3;

the programmer would write:

product.Quality = Quality.Good;
… providing that Quality Enum is declared something like:
public enum Quality
    JustBad, Poor, OK, Good, Excellent

Of course, you could set your enum values to some concrete numbers, like:

public enum Quality
    JustBad = 1, Poor = 2, OK = 3, Good = 4, Excellent = 5

… but in most cases you shouldn’t need to. Like I said, I see Enums only as a before-compilation, human <-> code communication, and therefore I believe no part of Enum should ever see the light of day (i.e. be exposed to the UI). And with that, there goes the need for binding to Enums…

Why would I want to bind to Enums anyway? Enum enumerators have no description (other than their names). If you need to provide spaces or even support localized descriptions, you’ll need to extend them significantly, so why not create a new class anyway? Here’s what I use instead of an Enum:

public sealed class Quality
    public const int JustBad = 1;
    public const int Poor = 2;
    public const int OK = 3;
    public const int Good = 4;
    public const int Excellent = 5;

    public Dictionary<int, string> Collection { get; private set; }

    public Quality()
        Collection = new Dictionary<int, string>()
            {JustBad,   "Just bad :("},
            {Poor,      "Poor"},
            {OK,        "OK"},
            {Good,      "Good"},
            {Excellent, "Excellent!"},

The programmer would still write:

product.Quality = Quality.Good;

so it makes it easy to refactor existing code. Additionally, you can put in any description for the values, support localization, and it’s easy bindable in Xaml - declare the class instance as a local resource:

<local:Quality x:Key="quality" />
and bind away:
<ListBox DisplayMemberPath="Value" 
         ItemsSource="{Binding Collection, Source={StaticResource quality}}" />