Click here to Skip to main content
Click here to Skip to main content

Binding and Using Friendly Enums in WPF

By , 27 Apr 2010
 

Introduction

As .NET developers, we know about and have probably used Enums before. For those that haven't used enums before, this is what MSDN has to say about them:

"The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char."

So when we use enums, we can actually do things like

enum Hardware {DiskDrive=1, Keyboard, GraphicsCard, Monitor};

Now this is all well and good, but imagine if we wanted to display a list of enums within a list, and we actually wanted to have more descriptive values, friendly names if you like, but still maintain the underlying enum value selected where required.

This article will show you how to do the following, using WPF:

  • Bind to a Enumeration of enum values
  • Display friendly names for enums, to aid the user experience

Bind to a Enumeration of Enum Values

The first thing that we might want to do is display a list of all possible enum values, such that a current value may be selected within this list, or allow the user to select a new enum value. This is easily achievable using the following technique:

<ObjectDataProvider x:Key="foodData"
                    MethodName="GetValues" 
                    ObjectType="{x:Type sys:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:FoodTypes" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

We can then use this to bind to within the XAML as follows:

<ComboBox x:Name="cmbFoodType"  
    ItemsSource="{Binding Source={StaticResource foodData}}"
	....
	....
</ComboBox>

Where I have a demo enum declared as follows (if you could just ignore the LocalizableDescriptionAttribute for the moment, more on that later) :

public enum FoodTypes : int
{
    Pizza = 1,
    Burger = 2,
    SpagBol = 3
}

This will result in the following:

Display Friendly Names for Enums, to Aid the User Experience

Now this does half the job, but from a users' point of view, some more descriptive text may actually aid the user experience, so what can we do about that. Well as luck would have it, Reflection and Attributes have the answer. We are able to adorn our enum with a special attribute namely a derived LocalizableDescriptionAttribute which inherits from DescriptionAttribute, which may be used as follows:

public enum FoodTypes : int
{
    [LocalizableDescription(@"Pizza", typeof(Resource))]
    Pizza = 1,

    [LocalizableDescription(@"Burger", typeof(Resource))]
    Burger = 2,

    [LocalizableDescription(@"SpagBol", typeof(Resource))]
    SpagBol = 3
}

I should point out that the original content of this article used the EnumMember which as several readers noted could not be localized for different cultures. Luckily one of those readers was the ultra talented Uwe Keim, who gave me some code for handling the localization of enums. This code is shown below for the LocalizableDescriptionAttribute. Thanks Uwe.

using System;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.ComponentModel;

namespace FriendlyEnumValues
{
    /// <summary>
    /// Attribute for localization.
    /// </summary>
    [AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
    public sealed class LocalizableDescriptionAttribute : DescriptionAttribute
    {
        #region Public methods.
        // ------------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the 
        /// <see cref="LocalizableDescriptionAttribute"/> class.
        /// </summary>
        /// <param name="description">The description.</param>
        /// <param name="resourcesType">Type of the resources.</param>
        public LocalizableDescriptionAttribute
		(string description,Type resourcesType) : base(description)
        {
            _resourcesType = resourcesType;
        }

        #endregion

        #region Public properties.

        /// <summary>
        /// Get the string value from the resources.
        /// </summary>
        /// <value></value>
        /// <returns>The description stored in this attribute.</returns>
        public override string Description
        {
            get
            {
                if (!_isLocalized)
                {
                    ResourceManager resMan =
                         _resourcesType.InvokeMember(
                         @"ResourceManager",
                         BindingFlags.GetProperty | BindingFlags.Static |
                         BindingFlags.Public | BindingFlags.NonPublic,
                         null,
                         null,
                         new object[] { }) as ResourceManager;

                    CultureInfo culture =
                         _resourcesType.InvokeMember(
                         @"Culture",
                         BindingFlags.GetProperty | BindingFlags.Static |
                         BindingFlags.Public | BindingFlags.NonPublic,
                         null,
                         null,
                         new object[] { }) as CultureInfo;

                    _isLocalized = true;

                    if (resMan != null)
                    {
                        DescriptionValue =
                             resMan.GetString(DescriptionValue, culture);
                    }
                }

                return DescriptionValue;
            }
        }
        #endregion

        #region Private variables.

        private readonly Type _resourcesType;
        private bool _isLocalized;

        #endregion
    }
}

The basic idea here is that this LocalizableDescriptionAttribute allows you to pass in a key and a resource type to look at, so the key value will index into the resource file and get the value of the resource file. This is shown below in the small resource file that is part of the demo code attached.

So now that we know we can do this with the enums, what about using this as a ComboBox within the XAML. Mmmm, well luckily there is another WPF trick we can use to aid here, which is IValueConverter. Let's see the revised XAML:

<Window.Resources>
    <local:EnumToFriendlyNameConverter x:Key="enumItemsConverter"/>

</Window.Resources>

<StackPanel>

    <!-- Enum Combobox picker -->
    <StackPanel Orientation="Vertical" Margin="2" Grid.Row="0" Grid.Column="0"   >

        <Label Height="Auto" Content="Food Types"/>
        <ComboBox x:Name="cmbFoodType"  
            ItemsSource="{Binding Source={StaticResource foodData}}"
	   		  ....
	    	  ....
            <ComboBox.ItemTemplate>

                <DataTemplate>
                    <Label  Content="{Binding   Path=.,Mode=OneWay, 
                                        Converter={StaticResource enumItemsConverter}}"
                            Height="Auto"
                            Margin="0" 
                            VerticalAlignment="Center"/>

                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>

</StackPanel>

Where the EnumToFriendlyNameConverter is as follows:

/// <summary>
using System;
using System.Windows.Data;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;

namespace FriendlyEnumValues
{
    /// <summary>
    /// This class simply takes an enum and uses some reflection to obtain
    /// the friendly name for the enum. Where the friendlier name is
    /// obtained using the LocalizableDescriptionAttribute, which holds the localized
    /// value read from the resource file for the enum
    /// </summary>
    [ValueConversion(typeof(object), typeof(String))]
    public class EnumToFriendlyNameConverter : IValueConverter
    {
        #region IValueConverter implementation

        /// <summary>
        /// Convert value for binding from source object
        /// </summary>
        public object Convert(object value, Type targetType,
                object parameter, CultureInfo culture)
        {
            // To get around the stupid WPF designer bug
            if (value != null)
            {
                FieldInfo fi = value.GetType().GetField(value.ToString());

                // To get around the stupid WPF designer bug
                if (fi != null)
                {
                    var attributes =
                        (LocalizableDescriptionAttribute[]) 
			fi.GetCustomAttributes(typeof 
			(LocalizableDescriptionAttribute), false);

                    return ((attributes.Length > 0) &&
                            (!String.IsNullOrEmpty(attributes[0].Description)))
                               ?
                                   attributes[0].Description
                               : value.ToString();
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// ConvertBack value from binding back to source object
        /// </summary>
        public object ConvertBack(object value, Type targetType, 
			object parameter, CultureInfo culture)
        {
            throw new Exception("Cant convert back");
        }
        #endregion
    }
}

The actual magic happens by the use of some Reflection. So if you need to run this in an XBAP, you will need to make sure it is run in FullTrust mode.

The final step of the puzzle is to make sure that the selected value makes its way back into the source object that may use one of the enum values. I am using a simple test setup comprised of a single ViewModel and a single test class. This should be obvious from the attached demo code.

Anyway, the part that ensures the test class receives the actual enum value, and not the friendly name, which it would not know what to do with, is a simple case of more databinding in the XAML. This is as follows:

<ComboBox x:Name="cmbFoodType"  
    ItemsSource="{Binding Source={StaticResource foodData}}"
    SelectedItem="{Binding Path=TestableClass.FoodType, Mode=TwoWay}" Height="Auto">
    <ComboBox.ItemTemplate>

        <DataTemplate>
            <Label  Content="{Binding   Path=.,Mode=OneWay, 
                                Converter={StaticResource enumItemsConverter}}"
                    Height="Auto"
                    Margin="0" 
                    VerticalAlignment="Center"/>

        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Where this now includes a binding to the SelectedItem, which is a TwoWay binding to the actual enum value within the test class.

So putting it all together, we now have a bound ComboBox which shows friendly values to the user, but maintains the correct enum values within the bound object, for the selected item.

And here is the test classes selected value, notice that it is the correct enum value:

I think this aids the user experience, a bit, hope it helps you out, as it has me.

Alternative Approach

Since I wrote this article, the legendary Andrew Smith (Infragistics....(Josh Smith even calls him a guru)), sent me an email with an alternative approach where he creates a MarkupExtension that does that same as this, so you might like to check out that at Andrews blog. The post is available using the link, http://agsmith.wordpress.com/2008/09/19/accessing-enum-members-in-xaml/, thanks Andrew.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
Member
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)
 
- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence
 
Both of these at Sussex University UK.
 
Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionGood, But why so complicated?memberCoddioz3 Nov '12 - 20:03 
GeneralRe: Good, But why so complicated?mvpSacha Barber4 Nov '12 - 4:03 
QuestionXaml namespace definitionsmembercamyyssa17 Oct '12 - 3:10 
AnswerRe: Xaml namespace definitionsmvpSacha Barber17 Oct '12 - 4:03 
GeneralRe: Xaml namespace definitionsmembercamyyssa17 Oct '12 - 4:58 
QuestionHow to reduce verbosity?memberBernhard Hiller6 Jun '12 - 0:06 
AnswerRe: How to reduce verbosity?mvpSacha Barber6 Jun '12 - 0:49 
QuestionHow to convert bzck? [modified]memberGoran _3 Mar '12 - 6:53 
AnswerRe: How to convert bzck?mvpSacha Barber3 Mar '12 - 21:25 
Questionusing locbaml + msbuild examplemembericeball126 Feb '12 - 6:10 
AnswerRe: using locbaml + msbuild examplemvpSacha Barber6 Feb '12 - 6:12 
QuestionNice work - one questionmemberGoran _1 Feb '12 - 23:16 
AnswerRe: Nice work - one questionmvpSacha Barber1 Feb '12 - 23:26 
GeneralRe: Nice work - one question [modified]memberGoran _2 Feb '12 - 0:04 
GeneralRe: Nice work - one questionmvpSacha Barber2 Feb '12 - 2:50 
GeneralMy vote of 5memberhoernchenmeister17 Jan '12 - 21:32 
GeneralRe: My vote of 5mvpSacha Barber2 Feb '12 - 2:50 
GeneralMy vote of 5memberFilip D'haene31 Dec '11 - 2:59 
GeneralRe: My vote of 5mvpSacha Barber31 Dec '11 - 3:48 
GeneralMy vote of 1memberkarthickraj.s13 Dec '11 - 2:49 
SuggestionLocalizableDescriptionAttribute easier version for public resourcesmemberandy bricklets26 Sep '11 - 22:51 
GeneralRe: LocalizableDescriptionAttribute easier version for public resourcesmvpSacha Barber26 Sep '11 - 23:06 
GeneralMy vote of 5memberEric Ouellet22 Sep '11 - 2:28 
GeneralMy vote of 5memberEugene Sadovoi13 Sep '11 - 13:00 
QuestionVery nicememberCIDev26 Aug '11 - 4:42 
AnswerRe: Very nicemvpSacha Barber26 Aug '11 - 6:14 
QuestionBind Enum to ComboBox (using VB WPF)memberMember 818079223 Aug '11 - 10:44 
AnswerRe: Bind Enum to ComboBox (using VB WPF)mvpSacha Barber23 Aug '11 - 10:51 
GeneralRe: Bind Enum to ComboBox (using VB WPF)memberMember 818079223 Aug '11 - 13:30 
GeneralRe: Bind Enum to ComboBox (using VB WPF)mvpSacha Barber23 Aug '11 - 19:58 
GeneralRe: Bind Enum to ComboBox (using VB WPF)mvpSacha Barber23 Aug '11 - 22:20 
GeneralRe: Bind Enum to ComboBox (using VB WPF)memberMember 818079224 Aug '11 - 11:09 
QuestionHow about TypeCoverters if used? [modified]membervallarasus19 Aug '11 - 22:27 
AnswerRe: How about TypeCoverters if used?mvpSacha Barber20 Aug '11 - 0:20 
GeneralMy vote of 5memberDavid Veeneman18 Aug '11 - 12:31 
GeneralSuccessfully implementedmemberleder1101110 May '11 - 0:22 
GeneralRe: Successfully implementedmvpSacha Barber10 May '11 - 1:10 
QuestionHow to pass the VALUE of Enum as a parameter in WPF ObjectDataProvider:memberMember 6599121 Oct '09 - 6:52 
QuestionHow to pass the VALUE of Enum as a parameter in WPF ObjectDataProvider:memberMember 6599121 Oct '09 - 6:41 
QuestionIt does not work correctly when ComboBox is placed in ListView/GridView.memberMaksAnt18 Jun '09 - 3:25 
QuestionLocalizing works fine, but styling..... [modified]memberHardy Wang2 Jan '09 - 8:46 
AnswerRe: Localizing works fine, but styling.....mvpSacha Barber4 Jan '09 - 0:52 
QuestionDesign time exceptionmemberSuperCriller25 Sep '08 - 4:03 
AnswerRe: Design time exceptionmvpSacha Barber25 Sep '08 - 4:35 
GeneralRe: Design time exceptionmemberChristian Holm Maagaard26 Sep '08 - 0:33 
GeneralRe: Design time exceptionmvpSacha Barber26 Sep '08 - 1:10 
GeneralRe: Design time exceptionmemberBernardTan26 Apr '10 - 20:03 
GeneralRe: Design time exceptionmvpSacha Barber26 Apr '10 - 20:16 
GeneralAn existing (simpler) solutionmemberGrant Frisken24 Sep '08 - 14:25 
GeneralRe: An existing (simpler) solutionmvpSacha Barber24 Sep '08 - 22:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 27 Apr 2010
Article Copyright 2008 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid