Telerik blogs

A common request in our support is to display a combo box, containing all values of a specific Enum. This is fairly easy with RadComboBox for Silverlight - all you need to do is to fill its ItemsSource collection with the Enum values. The best way to do this is to create a view model for the Enum:

using System;
using System.Collections;
using System.Linq;
using System.Reflection;

namespace SilverlightApplication1
{
    public class EnumModel
    {
        private Type enumType;

        public IEnumerable Values { get; private set; }

        [TypeConverter(typeof(TypeTypeConverter))]
        public Type EnumType
        {
            get
            {
                return this.enumType;
            }
            set
            {
                this.enumType = value;
                this.InitValues();
            }
        }

        private void InitValues()
        {
            this.Values = this.EnumType
                .GetFields(BindingFlags.Public | BindingFlags.Static)
                .Select<FieldInfo, object>(
                    (FieldInfo x) => x.GetValue(this.EnumType));
        }
    }
}

 

The trick here is the TypeConverter attribute on the EnumType property, that allows me to declare the EnumModel in XAML:

<UserControl.Resources> <local:EnumModel x:Key="EnumModel" 
 EnumType="System.Windows.Controls.ClickMode" /> </UserControl.Resources>

 

There are some limitations in this approach, though – you should modify the TypeTypeConverter class so that it can “recognize” the assemblies that might contain the enumerations, defined in XAML. See the TypeTypeConverter.cs in the attached source code for more information. Of course, if you create the EnumModel in the code behind you will be able to provide any Enum Type you want – in this case the modifications in the TypeTypeConverter class will not be necessary.

The rest is really simple:

<Grid DataContext="{StaticResource EnumModel}"> <telerikInput:RadComboBox ItemsSource="{Binding Values}" Width="100" Height="25" DisplayMemberPath="" /> </Grid>

 

Note the DisplayMemberPath attribute with empty string value – it has to be present, in order the combo box to be able properly to display its selected item. If you remove it, the control will display the Enum’s integer value in its selection box, instead of its text representation.

Here is the source code of the application


Comments

Comments are disabled in preview mode.