WPF对字母排序枚举说明

问题描述

我将枚举的描述标签用于创建该选项的更易理解的表示形式,例如:

''' <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

在Xaml端,我将其绑定到本地枚举,如下所示:

<ComboBox ItemsSource="{Binding Source={local:EnumBindingSource {x:Type local:MyCoolOptions}}}"

然后我使用类型转换器来显示描述,而不是像这样的枚举的字符串名称

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

到目前为止,一切都已显示,并且绑定到对象也起作用。但是现在我想按字母顺序对枚举的描述进行排序。我的情况很长,因此非常有帮助。通常我会像这样连接CollectionViewSource

<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>

但这只给了我从枚举中排序的字符串名称,而不是描述...

已经摆弄了一段时间,但似乎找不到在Enum Description上解决此问题的方法。当然,我可以创建一个类对象,并从中创建某种列表,但我的情况是枚举是绑定到UserControl的对象的属性,在该控件上显示了ComboBox,它是枚举的itemsource

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)