This is a mirror of official site: http://jasper-net.blogspot.com/

Binding and Using Friendly Enums in WPF

| Tuesday, April 12, 2011
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
}

Read more: Codeproject

Posted via email from Jasper-net

0 comments: