Custom MarkupExtesion For Binding Enum To ComboBox In WPF

In this article, you will learn about custom MarkupExtesion for binding enum to ComboBox in WPF.

Introduction to Markup Extension

In XAML, attributes of control are set by assigning a string literal, i.e., a constant value to that attribute. This is hard coding from XAML’s perspective (You can always change the attribute value from the code behind which makes it dynamic).

E.g.

  1. <Button Content = “Click Me”/>  

Sometimes, a developer may want to assign a dynamic value to these attributes which they can extract from other resources like XML, Databases, other controls etc.

E.g.

  1. <Label Name="lblId"  
  2.               Grid.Row="0"  
  3.               Grid.Column="0"  
  4.               Content="ID"  
  5.               HorizontalContentAlignment="Center"  
  6.               VerticalContentAlignment="Center"/>  
  7.        <TextBox Name="txtId"  
  8.                 Grid.Row="0"  
  9.                 Grid.Column="1"  
  10.                 Text="{Binding ProductId}"  
  11.                 HorizontalContentAlignment="Center"  
  12.                 VerticalContentAlignment="Center"/>  

In the above example, a developer may want to assign ‘ProductId’ to TextBox after fetching the product object from database at run time. In this case, he/she cannot hard code the text property of the text box at the development time.

Markup Extensions provide this facility to developers. They resolve property values at runtime by executing the code.

The syntax of Markup Extension

{MarkupEntensionClass Argument}

Some of the frequently used markup extensions in WPF are as follows -

  • Binding
  • StaticResource
  • DynamicResource
  • TemplateBinding
  • X: Static

Binding Enum to ComboBox in WPF

PROBLEMS

ComboBox is an ItemControl. To populate its drop-down list, we need to set its ItemSource property with any IEnumerable object which is a rule of thumb.

Now, Enum type is not IEnumerable which means that we cannot directly assign it to ItemSource property of ComboBox.

SOLUTION

  • To populate the ComboBox, we can simply use Enum.GetValues() to get an array of values of the constants in specified Enum. Then we can assign this Array to ItemSource of ComboBox since it is of type IEnumerable in code behind.

    CODE BEHIND
    1. Type enumType = typeof(enumName);  
    2. Array enumArray = Enum.GetValues(enumType);  
    3. cmbBoxName.ItemSource = enumArray;  
  • The above solution works well, but still, if we have hundreds of Enums in our project, we must write similar code everywhere, which creates a lot of redundant code. Instead, we can create one MarkupExtension which can convert the corresponding Enum to Array or List (which are of type IEnumerable). Then, use this MarkupExtension (which converts Enum to Array or List) in XAML to set ItemSource property to Enum.

    CODE
  • Extend your class with MarkupExtension
    1. public class BindingEnumToComboBoxExtension : MarkupExtension  
  • Create private field and property to hold Enum type,
    1. private Type _enumType;  
    2. public Type EnumType {  
    3.     get {  
    4.         return _enumType;  
    5.     }  
    6.     set {  
    7.         if (_enumType != _value) {  
    8.             if (value != null) {  
    9.                 Type enumType = Nullable.GetUnderlyingType(value) ? ? value;  
    10.                 if (!enumType.IsEnum) throw new ArgumentException("Type must be for an Enum.");  
    11.             }  
    12.             _enumType = value;  
    13.         }  
    14.     }  
    15. }  
  • Create Constructors that can be used in XAML to send Enum type to this class,
    1. public BindingEnumToComboBoxExtension () { }  
    2. public BindingEnumToComboBoxExtension (Type enumType)  
    3. {  
    4.    EnumType = enumType;  
    5. }  
  • Override ProvideValue method of MarkupExtension to convert Enum to Array,
    1. public override object ProvideValue(IServiceProvider serviceProvider)   
    2. {  
    3.     Type actualEnumType = Nullable.GetUnderlyingType(_enumType) ? ? _enumType;  
    4.     Array enumValues = Enum.GetValues(actualEnumType);  
    5.     if (actualEnumType == _enumType) return enumValues;  
    6.     Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);  
    7.     enumValues.CopyTo(tempArray, 1);  
    8.     return tempArray;  
    9. }  
  • Import dll into your project based on where it is. Mine is in the same assembly and Helper folder 
    1. xmlns:local="clr-namespace:BindingEnumToComboBox.Helper"  
  • Set ItemSource of CombBox.
    1. ItemsSource="{Binding Source={local:BindingEnumToComboBox {x:Type local:AccessRights}}}"  

Output
 
Let us now look at the output.
 
Without Markup Extension 
 
 Custom MarkupExtesion For Binding Enum To ComboBox In WPF
 
With Markup Extension
 
Custom MarkupExtesion For Binding Enum To ComboBox In WPF