Wpf combobox 绑定enum

可以采用ObjectDataProvider and MarkupExttension方法

1>ObjectDataProvider 示例

Wpf combobox 绑定enum_第1张图片

2>MarkupExttension示例

先写一个类

 public class GetEnumSourceExtension : System.Windows.Markup.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 GetEnumSourceExtension()
     {

     }

     public GetEnumSourceExtension(Type enumType)
     {
         this.EnumType = enumType;
     }

     public override object ProvideValue(IServiceProvider serviceProvider)
     {
         if (null == this._enumType)
             throw new InvalidOperationException("This EnumType must be specified.");
         Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
         Array enumVlues = Enum.GetValues(actualEnumType);

         if (actualEnumType == this._enumType)
             return enumVlues;

         Array tempArray = Array.CreateInstance(actualEnumType, enumVlues.Length + 1);

         enumVlues.CopyTo(tempArray, 1);

         return tempArray;


     }
 }

之后在Resource 中添加对他的引用

--------------------Xaml 代码示例----------------

 
     

之后在Combobox 中绑定静态资源

详情可以参考B站大神:十月的寒流

视频链接:WPF中如何将ComboBox绑定到后台的枚举类型从而生成选项?_哔哩哔哩_bilibili

你可能感兴趣的:(wpf)