显示枚举说明而不是名称
我有这样的数据绑定设置:
ItemsSource="{Binding Source={my:Enumeration {x:Type credit:OccupationCategory}}}" DisplayMemberPath="Description" SelectedValue="{Binding EmplType}" SelectedValuePath="Value"/>
它工作得很好。 对更大的软件设计进行更改我不能再生成任何生成INotifyPropertyChanged事件的内容,因此数据绑定类型不起作用。 相反,我手动设置selectedIndex并从代码构建选项,如下所示:
ItemsSource="{Binding Source={StaticResource ResidenceOwnershipType}}"/>
哪些参考
就列表选项的构建和所有数据的链接而言,这是有效的,但我不能让combobox在枚举中显示描述标记而不是实际文本。
我尝试过这样的事情:
DisplayMemberPath="Description"
但这不正确。 我该怎么做呢?
编辑:
我的枚举:
[DataContract] public enum ResidenceOwnershipType { [Description("")] None = 0, [Description("Owns Home Outright")] OwnsHomeOutright = 1, [Description("Buying Home")] BuyingHome = 2, [Description("Renting/Leasing")] //Weird order here reflects RouteOne website RentingLeasing = 4, [Description("Living w/Relatives")] LivingWithRelatives = 3, [Description("Owns/Buying Mobile Home")] MobileHome = 5, [Description("Unknown")] Unknown = 6 }
如果保留此ItemsSource
,则必须定义自定义ItemTemplate
因为DisplayMemberPath
只是一个路径,您将无法通过该路径检索描述。
至于模板应该是什么样的:你可以使用Binding.Converter
将TextBlock
绑定到枚举值(当前的DataContext
)和通过ValueConverter
Binding.Converter
。 代码只是一些反映来检索Description
( GetType
, GetCustomAttributes
等)
替代方法是一种自定义方法,可立即返回可用的集合(并在ObjectDataProvider
)或自定义标记扩展 ,它可以执行相同的操作。
方法示例如果我们正在讨论ComponentModel.DescriptionAttribute
:
public static class EnumUtility { // Might want to return a named type, this is a lazy example (which does work though) public static object[] GetValuesAndDescriptions(Type enumType) { var values = Enum.GetValues(enumType).Cast
这个答案是对我为自己的应用程序实现的HB答案的补充:
检查是否添加了Description属性:
Description = (value.GetType().GetMember(value.ToString())[0].GetCustomAttributes(true).OfType().Count() > 0 ? value.GetType().GetMember(value.ToString())[0].GetCustomAttributes(true).OfType ().First().Description : value)
并设置以下属性以确保使用正确的ID: SelectedValuePath="Value"