Reference nested enum type from XAML

前端 未结 1 785
囚心锁ツ
囚心锁ツ 2021-01-02 05:17

I can\'t seem to reference a public nested enum type from XAML. I have a class

namespace MyNamespace
{
  public class MyClass
  {
    public enum MyEnum
            


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 05:43

    A bit late here, but I used a markup extension and then used the following references in my xaml to reference the nested enum in a combobox:

    xmlns:MyNamespace="clr-namespace:MyNamespace;assembly=MyApp"
    

    ...

    ItemsSource="{Binding Source={resource:EnumBindingSource {x:Type MyNamespace:MyClass+MyEnum}}}"
    

    The code for the MarkupExtension was taken from here

    public class EnumBindingSourceExtension : MarkupExtension
    {
        private Type _enumType;
        public Type EnumType
        {
            get { return this._enumType; }
            set
            {
                if (value != this._enumType)
                {
                    if (null != value)
                    {
                        Type enumType = Nullable.GetUnderlyingType(value) ?? value;
                        if (!enumType.IsEnum)
                            throw new ArgumentException("Type must be for an Enum.");
                    }
    
                    this._enumType = value;
                }
            }
        }
    
        public EnumBindingSourceExtension() { }
    
        public EnumBindingSourceExtension(Type enumType)
        {
            this.EnumType = enumType;
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (null == this._enumType)
                throw new InvalidOperationException("The EnumType must be specified.");
    
            Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
            Array enumValues = Enum.GetValues(actualEnumType);
    
            if (actualEnumType == this._enumType)
                return enumValues;
    
            Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
            enumValues.CopyTo(tempArray, 1);
            return tempArray;
        }
    }
    

    0 讨论(0)
提交回复
热议问题