【发布时间】:2021-02-12 14:35:06
【问题描述】:
如何将枚举的格式化字符串描述绑定到组合框?我希望组合框显示描述,而不是枚举。
我有一个这样的枚举:
Public Enum Sandwiches
<ComponentModel.Description("Ham Sandwich")> HamSandwich
<ComponentModel.Description("Reuben")> Reuben
<ComponentModel.Description("Po’ Boy")> PoBoy
<ComponentModel.Description("Grilled Cheese")> GrilledCheese
End Enum
在描述字符串已经绑定到组合框后,我可以使用此函数将所选项目转换回枚举:
Public Function GetEnumFromDescriptionAttribute(Of T)(description As String) As T
Dim type As Type = GetType(T)
If Not type.IsEnum Then
Throw New InvalidOperationException()
End If
For Each fi As Reflection.FieldInfo In type.GetFields()
Dim descriptionAttribute As ComponentModel.DescriptionAttribute = TryCast(Attribute.GetCustomAttribute(fi, GetType(ComponentModel.DescriptionAttribute)), ComponentModel.DescriptionAttribute)
If descriptionAttribute IsNot Nothing Then
If descriptionAttribute.Description <> description Then
Continue For
End If
Return DirectCast(fi.GetValue(Nothing), T)
End If
If fi.Name <> description Then
Continue For
End If
Return DirectCast(fi.GetValue(Nothing), T)
Next
Return Nothing
End Function
但是我找不到将所有枚举绑定到组合框的干净方法。我知道一个经常被推荐的解决方案是将枚举和枚举描述转换为字典,然后将它们设置为 cbo DisplayMember 和 ValueMember。但我无法弄清楚如何真正做到这一点。,
我已经准备好了几十个关于如何做到这一点的部分解决方案;问题是它们都是用 C# 编写的,在 Option Strict 关闭的情况下使用隐式转换,并且没有显示完整的实现。所以我不可能将任何解决方案翻译成 .NET,因为我不知道定义了什么类型变量。
【问题讨论】:
-
This 你应该会感兴趣。
-
我添加了一个使用上面链接中的代码的答案。
-
OT,
Sandwiches是那个Enum的错误名称。应该是Sandwich。当且仅当它应用了Flags属性时,您应该将Enum的名称复数。如果您希望能够创建复合值,则可以使用该属性,从而实现多元化。如果您一次只使用一个值,那么您使用一个单数名称。 -
dim attr = GetType(Sandwiches).GetFields().Select(Function(f) f.GetCustomAttribute(Of DescriptionAttribute)?.Description).ToArray()。这是一个顺序枚举,value = SelectedIndex。最终删除第一个空值。 -
@jmcilhinney,很长时间以来,我显然一直在错误地命名我的枚举。谢谢你告诉我!