绑定到xaml中显示枚举的name属性

时间:2015-02-23 10:39:49

标签: c# wpf xaml enums

我有以下枚举:

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没有帮助。

1 个答案:

答案 0 :(得分:3)

创建一个实现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"/>