Define Enums as ItemsSource in WPF

Created with Sketch.

Enumerations are often used in applications to enable the user to select an item from a list of predefined values. This can be handled in the ViewModel by publishing a list of the enum values. But there is also another way that uses a XAML only approach.


public enum SampleEnum 
  Dog, Cat, Bird

In the resources of the window a data source will be created, which calls the GetValues method of the System.Enum class in order to obtain a list of enum values:

<Window x:Class="WpfApplication1.Window1" 
        Title="Bind to Enum" Height="250" Width="250">
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
        <x:Type TypeName="local:SampleEnum"/>

Binding to data source:

<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}" />

As the values of enums are usually not in a human readable form, we might want to used a converter to convert the values into (localized) strings.

[ValueConversion(typeof(SampleEnum?), typeof(String))]
public class SampleEnumConverter : IValueConverter
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    switch (value as SampleEnum?) { 
      case SampleEnum.Dog:
        return "Hund";
      case SampleEnum.Cat:
        return "Katze";
      case SampleEnum.Bird:
        return "Vogel";
    return null;

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    return DependencyProperty.UnsetValue;

How to use the converter:

  <myConverters:SampleEnumConverter x:Key="SampleEnumConverter"/>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}">
      <TextBlock Text="{Binding Path=., Converter={StaticResource SampleEnumConverter}}"/>

The ItemsSource binding shown in previous example remains unchanged, but we now add a custom ItemTemplate to the ComboBox.


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.