WPF Binding ItemsSource to Enum

I have found a very neat and simple way of binding an ItemControl to enum values. The trick is to use an ObjectDataProvider class which enables the creation of a XAML object available as a binding source.


To show an example first of all I need an enum:

public enum SampleEnum
{
Dog,
Cat,
Scrat,
Hefalump
}

To make it available for binding I will define it as a resource with an x:Key.

<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>

This code creates the ObjectDataProvider in the window with ObjectType property set to Enum and MethodName property set to GetValues method of the Enum class. Then a specific enum (SampleEnum) is set to MethodParameter attribute.

Having this resource we can bind it as an ItemsSource to a ListView and Combobox (or any other ItemsControl) by setting items source:

ItemsSource="{Binding Source={StaticResource dataFromEnum}}"

The XAML for the window is as follows:

<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>
<Grid>
<ListView ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
Margin="10,10,10,0" Height="80" VerticalAlignment="Top" />
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
Margin="10,0,10,80" Height="25" VerticalAlignment="Bottom" />
</Grid>
</Window>

The code behind for window is:

using System.Windows;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
public enum SampleEnum
{
Dog,
Cat,
Scrat,
Hefalump
}
}

And the result:

BindToEnum 

Happy Binding! ;-)

Monika

No Comments