Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created January 26, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomaslevesque/3926252bda9c8a485c6e to your computer and use it in GitHub Desktop.
Save thomaslevesque/3926252bda9c8a485c6e to your computer and use it in GitHub Desktop.
Markup extension that returns the values of an enum type
public class EnumValuesExtension : MarkupExtension
{
public EnumValuesExtension()
{
}
public EnumValuesExtension(Type enumType)
{
EnumType = null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (EnumType == null)
throw new InvalidOperationException("EnumType was not specified");
object[] values = Enum.GetValues(EnumType).Cast<object>().ToArray();
if (InsertNull == NullPosition.Before)
values = new object[] { null }.Concat(values).ToArray();
else if (InsertNull == NullPosition.After)
values = values.Concat(new object[] { null }).ToArray();
return values;
}
[ConstructorArgument("enumType")]
public Type EnumType { get; set; }
public NullPosition InsertNull { get; set; }
}
public enum NullPosition
{
None,
Before,
After
}
<ComboBox ItemsSource="{my:EnumValues my:MyEnum, InsertNull=Before}">
...
</ComboBox>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment