Menü Schließen

Define Enums as ItemsSource in WPF

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.

Example:

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" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:System="clr-namespace:System;assembly=mscorlib" 
        xmlns:local="clr-namespace:WpfApplication1" 
        Title="Bind to Enum" Height="250" Width="250">
  <Window.Resources>
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:SampleEnum"/>
      </ObjectDataProvider.MethodParameters>
   </ObjectDataProvider>
  </Window.Resources>
</Window>

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:

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

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

Ähnliche Beiträge

Schreibe einen Kommentar

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