Tuesday, June 2, 2009

Trips&Ticks: Set custom presented view for enum's fields in WPF.

Download source files - here.
Download bin files - here.

How you know, Enum can have underlying type as byte, sbyte, short, ushort, int, uint, long, or ulong. Often and often we need to present a view of Enum's values in visual elements. Usually enum's name isn't smooth for human look. As I have said we can't set for example string as underlying type and apply it as presented view.. We can use converter inherit from IValueConverter but it isn't comfortably as we need to reimplement it each time when Enum's count or order will be changed. I have implemented a simple class inherits from Attribute for set human smooth presented view:

[AttributeUsage( AttributeTargets.Field )]
public class ViewEnumAttribute : Attribute
{
public ViewEnumAttribute( String view )
{
View = view;
}

public String View
{
get;
private set;
}
}


We set AttributeTargets as Field for restrict scope of our attribute. Use of attribute is very simple:

public enum MyEnum
{
[ViewEnum( "My View Value 1" )]
MyEnumValue1,
[ViewEnum( "My View Value 2" )]
MyEnumValue2,
[ViewEnum( "My View Value 3" )]
MyEnumValue3,
}


and we extract this value when it is need:

private static object GetEnumView( Type fieldType, string fieldName )
{
FieldInfo info = fieldType.GetField( fieldName );

if( null != info )
{
foreach( ViewEnumAttribute attribute in info.GetCustomAttributes( typeof( ViewEnumAttribute ), false ) )
{
return attribute.View;
}
}

return fieldName;
}


For more details of realization you can look in attached above source files.

3 comments:

Eric De C# said...

The DescriptionAttribute is made exacly for that. There is no need to create a custom attrubute.

RredCat said...

You are right. DescriptionAttribute satisfies. Nice hint. But you still need to implement support this attribute and my article shows how it can be done.

konikula said...

Maybe it's good to make it with CustomAttribute, when you need multilanguage fuctionality...