How can I populate a WPF combo box in XAML with all the items from a given enum?

前端 未结 6 966
难免孤独
难免孤独 2020-12-23 15:11

Say I have an enum with four values:

public enum CompassHeading
{
    North,
    South,
    East,
    West
}

What XAML would be required to

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 15:23

    I think using an ObjectDataProvider to do that is really tedious... I have a more concise suggestion (yes I know, it's a bit late...), using a markup extension :

    
    

    Here is the code for the markup extension :

    [MarkupExtensionReturnType(typeof(object[]))]
    public class EnumValuesExtension : MarkupExtension
    {
        public EnumValuesExtension()
        {
        }
    
        public EnumValuesExtension(Type enumType)
        {
            this.EnumType = enumType;
        }
    
        [ConstructorArgument("enumType")]
        public Type EnumType { get; set; }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (this.EnumType == null)
                throw new ArgumentException("The enum type is not set");
            return Enum.GetValues(this.EnumType);
        }
    }
    

提交回复
热议问题