WPF Bind a combobox to an enumeration

I've often found myself needing to bind a combo box to an enumeration I've created. You can do this in WPF but it's a bit complicated. You end up needing to create a static resource. I had mine in a user control. First the enumeration I was using:

 namespace XmlCoderBI.Enums  
 {  
   /// <summary>  
   /// An enumeration that represents the type of conversion we're doing  
   /// </summary>  
   public enum ConversionType  
   {  
     /// <summary>  
     /// The binary  
     /// </summary>  
     [Description( "Binary" )]  
     Binary = 0,  
     /// <summary>  
     /// The base64  
     /// </summary>  
     [Description( "Binary" )]  
     Base64 = 1,  
     /// <summary>  
     /// The hexadecimal  
     /// </summary>  
     [Description( "Hexadecimal" )]  
     Hexadecimal = 2,  
     /// <summary>  
     /// The UTF-8  
     /// </summary>  
     [Description( "Hexadecimal" )]  
     UTF8 = 3,  
     /// <summary>  
     /// The UTF-16  
     /// </summary>  
     [Description( "Hexadecimal" )]  
     UTF16 = 4  
   }  
 }  


This is just an ordinary enum. Now you need to add this to your XAML references:

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:enums="clr-namespace:XmlCoderBI.Enums;assembly=XmlCoderBI" 

The first line adds a reference to the mscorlib library which lets us use Enums. The second is the reference to the library where you have your enumeration stored. Now to create the static resource and bind it to our combbox, I used mine in a user control, but this can go in any place you need it.

 <Usercontrol.Resources>  
     <objectdataprovider methodname="GetValues" objecttype="{x:Type System:Enum}"
     x:key="dataFromEnumImport">  
     <objectdataprovider .methodparameters="">  
         <x:type typename="enums:ConversionType">  
       </x:type></objectdataprovider>  
     </objectdataprovider></usercontrol>  
</UserControl.Resources>

<combobox itemssource="{Binding Source={StaticResource dataFromEnumImport}}"
 selecteditem="{Binding ImportFileType}" width="100" />  

You can see it's binding the ItemSource to our enum using the key we define in the static resource. The SelectedItem is also bound to a property I have defined in my DataContext. I use this for easy tracking of the selected value but you don't have to bind the SelectedItem.

Comments

Katie said…
Pretty cool. Thanks.

Popular Posts