Created
March 5, 2012 04:49
-
-
Save anonymous/1976666 to your computer and use it in GitHub Desktop.
A helper class to extract property-names of ViewModel for MVVM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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