[英]Show Enum Description Instead of Name
我的數據綁定設置如下:
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
只是一個路徑,您將無法通過該路徑檢索描述。
至於模板應該是什么樣子:您可以將TextBlock
綁定到枚舉值(當前的DataContext
)並使用Binding.Converter
其通過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<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"/>
這個答案是我為自己的應用程序實現的 HB 答案的補充:
檢查是否添加了 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.