c# - Windows 手机 8.1 : How to add data annotations to enum value types to get the appropriate string

标签 c# enums winrt-xaml windows-phone-8.1 win-universal-app

我有一个带有枚举的 Windows 通用应用程序。我在我的 Windows 8.1 和 Windows Phone 8.1 项目中都使用了这个枚举。

我已经看过这些链接 Windows Phone 8 - enums & DataAnnotations 但这似乎适用于 Windows Phone 8 Silverlight

这是我的枚举

   enum MyEnum
    {
         [Display(Description="Move forward")]
         Forward,
         [Display(Description="Move Backward")]
         Backward
    }

获取枚举值并返回描述的EnumHelper如下

    public static T GetAttribute<T>(this Enum enumValue)
        where T : Attribute
    {
        return enumValue
            .GetType()
            .GetTypeInfo()
            .GetDeclaredField(enumValue.ToString())
            .GetCustomAttribute<T>();
    }

我调用 GetAttribute 从我的枚举中获取字符串。我在显示数据时使用它,而不是将枚举显示为字符串,而是显示来自描述注释名称的字符串。

我能够为 Windows 8.1 编写一个转换器,它可以获取枚举值并在注释显示中给我描述。但是,我无法在 Windows Phone 8.1 中实现相同的行为。

在 Windows 8.1 中,以下命名空间将帮助我

using System.ComponentModel.DataAnnotations;

但是,由于它在 Windows Phone 8.1 中不存在。我如何实现类似的行为?有解决方法吗?

最佳答案

如果您在使用 DisplayAttribute 类时不依赖任何特殊行为(由任何其他库引起),您可以创建自己的版本。

using System;

[AttributeUsage(AttributeTargets.All)]
public class DisplayAttribute : System.Attribute 
{
    public string Name { get; private set; }

    public DisplayAttribute(string name)
    {
        this.Name = name;
    }
}

现在您不需要 System.ComponentModel.DataAnnotations 命名空间。

关于c# - Windows 手机 8.1 : How to add data annotations to enum value types to get the appropriate string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887725/

相关文章:

java - 无需预定义库的加密

c# - 无法创建抽象类的实例 - 来自文档

c# - 我可以将应用程序上传到 Windows 应用商店而不使用 .net native 工具链进行编译吗?

c# - 后退按钮专注于列表操作

c# - asp.net 应用程序在本地主机上识别用户,但在没有硬编码用户名/密码的情况下无法在服务器上识别用户

c# - 如何使用 DNN 和 C# 创建站点地图

python - 验证值在 Python 枚举值中

C# 禁用关键字功能

c - enum 是常数还是常数变量或其他什么?在以下代码中出现错误

winrt-xaml - Windows Phone 8.1 通用应用程序中没有建议的键盘输入范围