我的数据绑定设置如下:
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"
但这不正确。我该怎么做呢?
编辑:
My Enum:
[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
}
答案 0 :(得分:13)
如果您保留此ItemsSource
,则必须定义自定义ItemTemplate
,因为DisplayMemberPath
只是您无法检索说明的路径。
关于模板应该是什么样的:您可以将TextBlock
绑定到枚举值(当前DataContext
)并使用Binding.Converter
通过ValueConverter
管道。代码只是一些反映,以检索Description
(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"/>
答案 1 :(得分:1)
这个答案是H.B.我为自己的应用程序实现的答案的补充:
检查是否添加了Description属性:
Description = (value.GetType().GetMember(value.ToString())[0].GetCustomAttributes(true).OfType<DescriptionAttribute>().Count() > 0 ?
value.GetType().GetMember(value.ToString())[0].GetCustomAttributes(true).OfType<DescriptionAttribute>().First().Description
: value)
并设置以下属性以确保使用正确的ID:SelectedValuePath="Value"