yas*_*sir 5 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
}
Run Code Online (Sandbox Code Playgroud)
获取枚举值并返回描述的EnumHelper如下
public static T GetAttribute<T>(this Enum enumValue)
where T : Attribute
{
return enumValue
.GetType()
.GetTypeInfo()
.GetDeclaredField(enumValue.ToString())
.GetCustomAttribute<T>();
}
Run Code Online (Sandbox Code Playgroud)
我调用 GetAttribute 从枚举中获取字符串。我在显示数据时使用它,而不是将枚举显示为字符串,而是显示描述注释名称中的字符串。
我能够为 Windows 8.1 编写一个转换器,它可以获取枚举值并在注释显示中给出描述。但是我无法在 Windows Phone 8.1 中实现相同的行为。
在 Windows 8.1 中,以下命名空间将帮助我
using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)
但由于 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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在您不应该需要System.ComponentModel.DataAnnotations名称空间。
| 归档时间: |
|
| 查看次数: |
1353 次 |
| 最近记录: |