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 3: In the MainPage.xaml, design the xaml as shown below:
Step 4: In the loaded event, write the following code:
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:
Download the source code
Tweet
2 comments:
How do we do this with MVVM?
can you tell the advantages of using reflection for this, it will be very healpful
Post a Comment