【问题标题】:Binding to display name attribute of enum in xaml绑定到 xaml 中枚举的显示名称属性
【发布时间】:2015-04-24 15:52:11
【问题描述】:

我有以下枚举:

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&lt;DescriptionAttribute&gt;().Description;。 但是,这对 XAML 没有帮助。

【问题讨论】:

标签: c# wpf xaml enums


【解决方案1】:

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

【讨论】:

  • 这会导致空引用异常?!
  • @mosquito87 这很奇怪,我想到的唯一可能是Convert 方法的value 参数为null,或者由于某种原因GetAttributeOfType 方法返回null.. . 你能用调试器来查明引发异常的确切行吗?
  • 好吧,尽管看起来很傻,Convert 方法试图得到一个System.ComponentModel.DescriptionAttribute(我盲目地按照你的使用示例),而枚举成员用System.ComponentModel.DataAnnotations.DisplayAttribute 装饰,所以难怪GetAttributeOfType 返回null。这两个类都具有Description 属性的事实掩盖了这个问题......另外,我认为你的意思是获取Name 属性。我已经相应地更新了答案。
猜你喜欢
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-05
相关资源
最近更新 更多