我有这样的数据绑定设置:
ItemsSource="{Binding Source={my:Enumeration {x:Type credit:OccupationCategory}}}" DisplayMemberPath="Description" SelectedValue="{Binding EmplType}" SelectedValuePath="Value"/>
它工作得很好.对更大的软件设计进行更改我不能再生成任何生成INotifyPropertyChanged事件的内容,因此数据绑定类型不起作用.相反,我手动设置selectedIndex并从代码构建选项,如下所示:
ItemsSource="{Binding Source={StaticResource ResidenceOwnershipType}}"/>
哪些参考
<UserControl.Resources> <ObjectDataProvider x:Key="ResidenceOwnershipType" MethodName="GetValues" ObjectType="{x:Type System:Enum}" > <ObjectDataProvider.MethodParameters> <x:Type TypeName="credit:ResidenceOwnershipType" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </UserControl.Resources>
就列表选项的构建和所有数据的链接而言,这是有效的,但我无法让组合框在枚举中显示描述标记而不是实际文本.
我尝试过这样的事情:
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)和通过@L_403_1@的管道.代码只是一些反映来检索描述(GetType,GetCustomAttributes等)
替代方案是一种自定义方法,可以立即返回可用的集合(并在ObjectDataProvider中使用)或自定义markup extension,它可以执行相同的操作.
方法示例如果我们正在讨论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<object>(); var valuesAndDescriptions = from value in values select new { Value = value,Description = value.GetType() .GetMember(value.ToString())[0] .GetCustomAttributes(true) .OfType<DescriptionAttribute>() .First() .Description }; return valuesAndDescriptions.ToArray(); } }
<ObjectDataProvider x:Key="Data" MethodName="GetValuesAndDescriptions" ObjectType="local:EnumUtility"> <ObjectDataProvider.MethodParameters> <x:TypeExtension TypeName="local:TestEnum" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider>
<ListBox ItemsSource="{Binding Source={StaticResource Data}}" DisplayMemberPath="Description" SelectedValuePath="Value"/>