Enum’s and MarkupExtension
Here is quick sample to get all the values from an enum using MarkupExtension. This returns a Dictionary
public class EnumValuesExtension : MarkupExtension
{
public string EnumName { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
IXamlTypeResolver xamlResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
Type t = xamlResolver.Resolve(EnumName);
return t.GetFields().Where(field => field.IsLiteral).ToDictionary(x => (int)x.GetValue(null), x => x.Name);
}
}
If we have a enum like below
public enum Days
{
Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri
}
We can use it in xaml like this. ‘local’ is the xmlns declaration pointing to the namespace
<ComboBox Width=”150″ Height=”25″ DisplayMemberPath=”Value”
ItemsSource=”{local:EnumValues EnumName=’local:Days’}”/>