Reputation: 2286
Were this not a window phone 8 project, If I wanted to display a human readable version of an enum I would use a niftt DataAnnotation like such
public enum InstallationType
{
[Display(Description="Forward of Bulk Head")]
FORWARD = 0,
[Display(Description="Rear of Bulk Head")]
REAR = 1,
[Display(Description="Roof Mounted")]
ROOF = 2,
}
and pull them out using something to the effect of:
public static string GetDescriptionFromEnumValue(Enum value)
{
DisplayAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DisplayAttribute), false)
.SingleOrDefault() as DisplayAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
Easy, But my problem is that System.ComponentModel.DataAnnotation is not available in Windows Phone. I have tried using a Portable Class Library but when I target WP8 I loose the ability to hit that namespace.
What other options are there?
Upvotes: 2
Views: 929
Reputation: 6178
You can try following one.
Suppose you have an enum with description like below
public enum FriendType : byte
{
[Description("Friend Only")]
Freind,
[Description("Friend InComing")]
InComing,
[Description("Friend OutGoing")]
OutGoing,
[Description("Friend Block")]
Block
}
Now Create a generic class and methods to read the description of a enum
public static class EnumHelper<T>
{
//to get full description list
public static List<string> GetEnumDescriptionList()
{
var type = typeof(T);
var names = Enum.GetNames(type).ToList();
var list = new List<string>();
foreach (var name in names)
{
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
var temp = customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
list.Add(temp);
}
return list;
}
//for single description
public static string GetEnumDescription(string value)
{
var type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null) return string.Empty;
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
}
Then call the medthod with enum type.
var descriptionList = EnumHelper<FriendType >.GetEnumDescription();
var singleDescription = EnumHelper<FriendType>.GetEnumDescription("block");
Upvotes: 0
Reputation: 222582
System.ComponentModel.DataAnnotation is not available in Windows Phone , you can make use of Linq. Follow this example to bind enum,
Upvotes: 2