我有这样的数据绑定(bind)设置:
ItemsSource="{Binding Source={my:Enumeration {x:Type credit:OccupationCategory}}}"
DisplayMemberPath="Description"
SelectedValue="{Binding EmplType}"
SelectedValuePath="Value"/>
而且效果非常好。对较大的软件设计进行更改我不能再拥有任何生成 INotifyPropertyChanged 事件的东西,因此这种类型的数据绑定(bind)不起作用。相反,我手动设置 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
只是一条路径,您将无法通过该路径检索描述。
至于模板应该是什么样子:您可以将 TextBlock
绑定(bind)到枚举值(当前 DataContext
)并通过 ValueConverter
进行管道传输。使用 Binding.Converter
。该代码只是一些反射,用于检索 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"/>
关于c# - 显示枚举描述而不是名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11439920/