Binding an ItemsSource to an Enum
This rather quick post is about enabling an Enum
to be set as the ItemsSource
of a ComboBox, ListBox etc. You can find the sample code on Github.
Our implementation will result in the following xaml code:
In the above code snippet, the ItemsSource is bound to the enum Animals
by introducing a new MarkupExtension called EnumToItemsSourceExtension
:
By inheriting from the MarkupExtension
class, we have to implement the abstract method ProvideValue
. Using the Enum.GetValues()
method, we retrieve an array of the values of the constants in the provided enumeration (Animals) and we return it, so that the ItemsSource can bind to it.