绑定以显示 xaml 中枚举的名称属性

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 和数据绑定来显示我 window 中的枚举:

<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.

没有帮助

创建一个 class 实现 System.Windows.Data.IValueConverter 接口并将其指定为绑定的转换器。或者,为了更容易使用,您可以创建一个 "provider" class 来实现 System.Windows.Markup.MarkupExtension(实际上您可以只用一个 class 来完成这两个操作)。您的最终结果可能类似于此示例:

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"/>