[英]Binding to display name attribute of enum in xaml
我有以下枚舉:
public enum ViewMode
{
[Display(Name = "Neu")]
New,
[Display(Name = "Bearbeiten")]
Edit,
[Display(Name = "Suchen")]
Search
}
我正在使用xaml和數據綁定在我的窗口中顯示枚舉:
<Label Content="{Binding CurrentViewModel.ViewMode}" Grid.Column="2" VerticalContentAlignment="Bottom" Height="43" HorizontalContentAlignment="Right"/>
但是這不顯示顯示名稱屬性。 我怎么能這樣做?
在我的viewModel中,我可以使用擴展方法獲取顯示名稱屬性:
public static class EnumHelper
{
/// <summary>
/// Gets an attribute on an enum field value
/// </summary>
/// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
/// <param name="enumVal">The enum value</param>
/// <returns>The attribute of type T that exists on the enum value</returns>
public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute
{
var type = enumVal.GetType();
var memInfo = type.GetMember(enumVal.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
return (attributes.Length > 0) ? (T)attributes[0] : null;
}
}
用法是string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;
。 但是,這對XAML沒有幫助。
創建一個實現System.Windows.Data.IValueConverter
接口的類,並將其指定為綁定的轉換器。 (可選)為了便於使用,您可以創建一個實現System.Windows.Markup.MarkupExtension
的“provider”類(實際上,您只需要使用一個類)。 您的最終結果可能類似於以下示例:
public class MyConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((Enum)value).GetAttributeOfType<DisplayAttribute>().Name;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
然后在XAML中:
<Label Content="{Binding CurrentViewModel.ViewMode, Converter={local:MyConverter}}" Grid.Column="2" VerticalContentAlignment="Bottom" Height="43" HorizontalContentAlignment="Right"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.