Last active
August 29, 2015 14:26
-
-
Save Jalalx/3b5aa0d137c5e4a033c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
Sample of use: | |
<ComboBox ItemsSource="{Binding Source={ Extensions:ByteEnumerationExtention {x:Type type:MyEnum} }}" DisplayMemberPath="Description" | |
SelectedValuePath="Value" SelectedValue="{Binding SelectedItemInViewModel}"/> | |
public enum MyEnum : short | |
{ | |
[Description("گزینه 1")] | |
Item1 = 1, | |
[Description("گزینه 2")] | |
Item2 = 2 | |
} | |
*/ | |
public class ByteEnumerationExtention : MarkupExtension | |
{ | |
public ByteEnumerationExtention(Type enumType) | |
{ | |
this.enumType = enumType; | |
} | |
private Type enumType; | |
public Type EnumType | |
{ | |
get { return enumType; } | |
private set | |
{ | |
enumType = value; | |
} | |
} | |
public override object ProvideValue(IServiceProvider serviceProvider) | |
{ | |
return (from x in Enum.GetValues(EnumType).OfType<Enum>() | |
select new EnumerationMember | |
{ | |
Value = GetValue(x), | |
Description = GetDescription(x) | |
}).ToArray(); | |
} | |
private byte? GetValue(object enumValue) | |
{ | |
return Convert.ToByte(enumValue.GetType().GetField("value__").GetValue(enumValue)); | |
} | |
public object GetObjectValue(object enumValue) | |
{ | |
return enumValue.GetType().GetField("value__").GetValue(enumValue); | |
} | |
public string GetDescription(object enumValue) | |
{ | |
var descAttrib = EnumType.GetField(enumValue.ToString()) | |
.GetCustomAttributes(typeof(DescriptionAttribute), false) | |
.FirstOrDefault() as DescriptionAttribute; | |
return descAttrib != null ? descAttrib.Description : enumValue.ToString(); | |
} | |
} | |
public class EnumerationMember | |
{ | |
public string Description { get; set; } | |
public byte? Value { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment