Tuesday, August 31, 2010

WPF - Loading Combo Box Items with Enum Members

In this post, we will discuss how we can load the items of a combo box with members of an Enumeration. For developing our applications, we need to show data which might be selected e.g. Gender (Male / Female).

Let's create an enumeration, named Gender in our View Model.

namespace WpfApplication1
public class EnumsViewModel
public enum Gender

Now let's create a view, EnumsView. We add a combo box and specify the members of the enumeration specified above as its data source. In order to do that, we need to use ObjectDataProvider in the Resource section. We can use GetValues() method of enum to get the members of the enumeration. We specify the key of this object as GenderList. Please don't forget to have a look at how we are accessing nested Gender enumeration with + syntax (local:EnumsViewModel+Gender).

<Window x:Class="WpfApplication1.EnumsView"
Title="EnumsView" Height="300" Width="300">
<ObjectDataProvider x:Key="GenderList" MethodName="GetValues" ObjectType="{x:Type System:Enum}" >
<x:Type TypeName="local:EnumsViewModel+Gender" />
<Label Height="22" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" Width="55">Gender</Label>
<ComboBox Height="19" Margin="73,15,57,0" Name="cmbGender" VerticalAlignment="Top" >
<Binding Source="{StaticResource GenderList}" />

As you can see that we are using the GenderList, the list of members of enum (Gender) as the data source of the Combo box. When we run the application, it is loaded as follows:

It seems WPF has a designer issue with "+" syntax for inner classes. The designer has not been able to load the view when I used this:

This issue is already reported on Connect site:

No comments: