Silverlight 4: Binding Enum with ComboBox

In this article, we will explore the mechanism of Binding Enumeration data with the ItemsControls family in Silverlight. Enum is used to store constant type of data with integer values as its contents For e.g. Department values like IT, System etc. can be stored in Enum and can be used as constants in your application code. If this data needs to be displayed in a UI using DataBinding, we can make use of reflection to achieve it. The Enum can be read as a Type and the contents in it can be read as Fields using BindingFlag. After reading these Fields, then they can be added to any collection class e.g. ObservableCollection<T> and then this can be used for DataBinding with Silverlight UI elements. The code is as shown below:

Step 1: Open VS2010 and create a Silverlight project, name it as ‘SL4_Enum_Binding_ComboBox’.

Step 2: In the MainPage.xaml.cs add the following Enum:

Silverlight ComboBox Enum

Step 3: In the MainPage.xaml, design the xaml as shown below:

Silverlight ComboBox Enum

Step 4: In the loaded event, write the following code:

Enum ObservableCollection

The above code reads the Enum ‘Department’ as Type and then using reflection, all fields are read. Here I must say that reflection, if used well, is a gift to programmers, using which types can be read easily. The above code defines an ObservableCollection of name Departments which is used to store values retrieved from the Enum in the FieldInfo. The ObservableCollection is the bound with the UI. The above xaml contains ComboBox which is bound with this ObservableCollection.

Step 5: Run the application, and the following result will be displayed:

Silverlight Enum Demo
Download the source code




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

2 comments:

Lakshmi said...

How do we do this with MVVM?

Anonymous said...

can you tell the advantages of using reflection for this, it will be very healpful