绑定到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的"提供者"类(实际上,只需一个类就可以同时实现这两个)。您的最终结果可能类似于以下示例:

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

最新更新