Displaying Enum Values using Data Binding

Some of the FAQs about data binding are:

• How do I bind to a method?
• How do I bind between instantiated controls?
• How do I bind an ItemsControl to an enum?

I put together a quick sample that should answer the above questions:

<Window

xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"

xmlns:sys="clr-namespace:System;assembly=mscorlib"

SizeToContent="WidthAndHeight"

Title="Show Enums in a ListBox using Binding">

<Window.Resources>

<ObjectDataProvider MethodName="GetValues"

ObjectType="{x:Type sys:Enum}"

x:Key="AlignmentValues">

<ObjectDataProvider.MethodParameters>

<x:Type TypeName="HorizontalAlignment" />

</ObjectDataProvider.MethodParameters>

</ObjectDataProvider>

</Window.Resources>

<Border Margin="10" BorderBrush="Aqua"

BorderThickness="3" Padding="8">

<StackPanel Width="300">

<TextBlock>Choose the HorizontalAlignment

value of the Button:</TextBlock>

<ListBox Name="myComboBox" SelectedIndex="0" Margin="8"

ItemsSource="{Binding Source={StaticResource

AlignmentValues}}"/>

<Button Content="Click Me!"

HorizontalAlignment="{Binding ElementName=myComboBox,

Path=SelectedItem}"/>

</StackPanel>

</Border>

</Window>

The ListBox and the Button are hooked up such that you can “control” the HorizontalAlignment value of the Button by selecting a value in the ListBox. This is a screenshot of the example:

So, the answers to the questions are:

• You bind to a method using the ObjectDataProvider. In the example above, we are binding to Enum.GetValues. Specifically, Enum.GetValues(typeof(HorizontalAlignment)).
• You bind the property of a control to a property of another control using the ElementName property of the Binding class. In the example above, the Button HorizontalAlignment property is bound to the SelectedItem property of the ComboBox.
• You bind to an enum by binding to the Enum.GetValues method.