[WPF] Binding ItemsSource to Enum

By | January 27, 2015

Advertisement from Google

Suppose you need to bind ItemsSource dependency property to enum’s values. For example in ComboBox.

You have following enum:

public enum ExampleEnum
{
     Red,
     Green,
     Yellow
}

Advertisement from Google

Now you can use ObjectDataProvider

<Window x:Class="ExampleApplication.Window"
 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:ExampleApplication"
 Title="Bind to Enum" Height="250" Width="250">
  <Window.Resources>
     <ObjectDataProvider x:Key="enumValues"
       MethodName="GetValues" ObjectType="{x:Type System:Enum}">
          <ObjectDataProvider.MethodParameters>
               <x:Type TypeName="local:ExampleEnum"/>
          </ObjectDataProvider.MethodParameters>
     </ObjectDataProvider>
  </Window.Resources>
</Window>

and now in ItemsSource propety use following binding syntax:

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

One thought on “[WPF] Binding ItemsSource to Enum

  1. Ryan

    Your sample works well epecxt you need match up your “x:Key” name in the with the ListView’s ItemContainerStyle={DynamicResource StyleName}I copied the sample code & changed that to make it work. Great solution!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *