I use the description tag for an enum to create a more human readable representation of that option, for example:
''' <summary>
''' Indicates something cool
''' </summary>
<TypeConverter(GetType(EnumDescriptionTypeConverter))>
Public Enum MyCoolOptions
<Description("B - This brings you to the moon")>
AwesomeOption1 = 0
<Description("A - This brings you to Mars")>
AwesomeOption2 = 1
End Enum
In the Xaml side i have bind it to the local enum like this:
<ComboBox ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:MyCoolOptions}}}"
Then i use a Type Converter to display the description instead of the string name of the enum like this:
Public Class EnumDescriptionTypeConverter
Inherits EnumConverter
Public Sub New(ByVal type As Type)
MyBase.New(type)
End Sub
Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
If destinationType = GetType(String) Then
If value IsNot Nothing Then
Dim fi As FieldInfo = value.[GetType]().GetField(value.ToString())
If fi IsNot Nothing Then
Dim attributes As DescriptionAttribute() = CType(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
Return If(((attributes.Length > 0) AndAlso (Not String.IsNullOrEmpty(attributes(0).Description))), attributes(0).Description, value.ToString())
End If
End If
Return String.Empty
End If
Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function
End Class
So far so good, everything is being displayed and binding to an object also works. But now I want to sort the description of the enum alphabetically. I my case i have a long list so it would be very helpful. Normally I would hookup an CollectionViewSource
like so:
<CollectionViewSource x:Key="MyCoolOptionsEnum">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription />
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.Source>
<ObjectDataProvider MethodName="GetName" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyCoolOptions" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</CollectionViewSource.Source>
</CollectionViewSource>
But this only gives me the string name sorted from the enum, not the description...
Have been fiddling with it for a while but can't seem to find a way to fix this on Enum Description. Sure i can create a class object of it and from that create a list of some sort, but i my case the enum is a property of an object that is bind to the Usercontrol on which a ComboBox is display that get's it's itemsource from the enum.