Recently Karl Shifflett, a budding WPF developer and author of articles about WPF, posted an article on CodeProject. The article demonstrates how to bind a ComboBox to a sorted collection of enum values. His approach aims to be XAML-only, and it came pretty close. After reading his article I realized that it is possible to take it one final step further toward being purely XAML.
His technique involves using an ObjectDataProvider to call a method in the code-behind which returns a sorted collection of enum values. The method in the code-behind is responsible for sorting the enum values. His approach is perfectly valid, and works just fine, but it does involve a dependency on the code-behind. For something as presentation-oriented as displaying a sorted list of values, I don’t think that the XAML file should depend on the code-behind.
Here is a XAML-only approach to solving the problem. First we need an unsorted enum:
Next we need to create a sorted list of values in the enum, and then bind a ComboBox to that list:
(The System.ComponentModel namespace referenced above lives in the WindowsBase assembly. I had to clip the assembly name in the image so that it would fit in my blog properly.)
The basic idea here is that we create a CollectionViewSource which, in turn, uses an ObjectDataProvider to get an unsorted list of values for the Animals enum. The CollectionViewSource also has a SortDescription added to it. That causes the list of enum values to be sorted in ascending order, based on their names.
Once that data source is declared we bind a ComboBox to it. The ComboBox looks like this when you run the demo app:
You can download the demo app here: Sorted enum in ComboBox (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress it.