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
{
Male,
Female
}
}
}

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"
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="EnumsView" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="GenderList" MethodName="GetValues" ObjectType="{x:Type System:Enum}" >
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:EnumsViewModel+Gender" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<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" >
<ComboBox.ItemsSource>
<Binding Source="{StaticResource GenderList}" />
</ComboBox.ItemsSource>
</ComboBox>
</Grid>
</Window>

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:
https://connect.microsoft.com/VisualStudio/feedback/details/361509/xaml-designer-cannot-handle-typename-with-nested-classes?wa=wsignin1.0

No comments: