Skip to content

Instantly share code, notes, and snippets.

Created March 5, 2012 04:49
Show Gist options
  • Save anonymous/1976666 to your computer and use it in GitHub Desktop.
Save anonymous/1976666 to your computer and use it in GitHub Desktop.
A helper class to extract property-names of ViewModel for MVVM.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Utils {
[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
public class PropertyTagAttribute : System.Attribute {
public PropertyTagAttribute(Type inTagType, int inTagValue) {
if (inTagType == null) {
throw new NullReferenceException();
}
var info = inTagType.GetTypeInfo();
if (!Enum.IsDefined(inTagType, inTagValue)) {
throw new ArgumentException("Undefined Enum value");
}
this.Tag = (Enum)Enum.ToObject(inTagType, inTagValue);
}
public Enum Tag { get; private set; }
}
public class PropertyTagMapper {
private Dictionary<Enum, string[]> mTagMap;
public PropertyTagMapper(Type inType) {
mTagMap = (
inType.GetTypeInfo().DeclaredProperties
.Where(p => p.CanRead)
.SelectMany(p => {
return p.GetCustomAttributes<PropertyTagAttribute>(true).Select(attr => {
return new KeyValuePair<Enum, string>(attr.Tag, p.Name);
});
})
.GroupBy(pair => pair.Key, pair => pair.Value)
.ToDictionary(pair => pair.Key, pair => pair.ToArray())
);
}
public string[] ToProprtyNames(Enum inTag) {
string[] props;
if (mTagMap.TryGetValue(inTag, out props)) {
return props;
}
else {
return new string[0];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment