Imagine we have an Enum type and we want to use that Enum type to be an ItemsSource of ListBox or ComboBox. Bolow is an example of an Enum type called AirFareBookingStatus
What we want to achieve is to populate all the statuses from the Enum to a ListBox or ComboBox.
There is already a solution for this from the Silverlight forum. The idea is to go through all the Field and put them into a IEnumerable of KeyValuepair
Then all we have to do is assign the result to ListBox or ComboBox ItemsSource
That would be good enough for it to work.
But we can even make it more generic by creating a helper function as below
Then, we can call that function for every Enum type we have. For example
There is still one problem left we have. The item still displays the whole object, so make it display correctly, we need to create DataTemplate resource
Then apply that DataTemplate to the ItemTemplate of ListBox or ComboBox as below
That’s it. Hope that helps.
Now, I have run into another problem. Doing that way above is all good, except the name won’t be as flexible. So, I am going to Description attribute to display data instead of the normal name of the Enum. To do that, I’ve changed a bit of my Enum like below
Next, I changed a bit in my helper function as well. It’ll get the Description attribute and make it to be Key
Finally, we will have something like this
That’s it. Let me know if you have any comments.