我有一个带有枚举的 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/