Monday, August 25, 2008

Enum as a ComboBox.ItemSource in WPF

Currently I'm working on my first project with WPF and study it on a practice. In this short article I want to give example how in XAML make ComboBox list values (or names) of enum.

ItemsControl.ItemsSource uses IEnumerable as source of items to list in ItemsControl (which ComboBox is derived from). In C# you can do this very simply:

comboBox.ItemsSource = Enum.GetNames( typeof( Dock ) );

You can do the same using only XAML:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="ItemsSource test" Height="70" Width="150" WindowStyle="ToolWindow">
<Window.Resources>
<ObjectDataProvider x:Key="DockNames"
MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="{x:Type Dock}" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox Margin="5" Width="120" Height="23" Name="comboBox"
HorizontalAlignment="Left" VerticalAlignment="Top"
ItemsSource="{Binding Source={StaticResource DockNames}}"
SelectedIndex="0">
</ComboBox>
</Grid>
</Window>

In this sample ObjectDataProvider is a wrapper for a method call and to assign this data provider to ItemsSource binding is used. As you can see XAML version of requires more lines of code. But it is usefull if development team strictly follows the rule that interface view must be defined in XAML without code on C#.