WPF的ComboBox绑定Enum枚举

ComboBox绑定Enum枚举,最常想到的方法就是在viewmodel中定义一个数组属性,然后在xaml中直接用ComboBox的ItemsSource来绑定,这种方法需要在viewmodel中额外定义一个属性来供xaml绑定。

现在介绍一个直接在xaml上绑定的枚举,不需要在viewmodel中去额外定义属性。

实现效果如下:

代码实现如下:

cs 复制代码
   public class EnumBindingSourceExtension : MarkupExtension
   {
       private Type? _enumType;

       public Type? EnumType
       {
           get => _enumType;
           set
           {
               if (value != _enumType)
               {
                   if (value != null)
                   {
                       Type enumType = Nullable.GetUnderlyingType(value) ?? value;
                       if (!enumType.IsEnum)
                       {
                           throw new Exception("类型必须是枚举");
                       }
                   }
                   _enumType = value;
               }
           }
       }

       public EnumBindingSourceExtension(Type enumType)
       {
           EnumType = enumType;
       }

       public EnumBindingSourceExtension()
       {
       }

       public override object ProvideValue(IServiceProvider serviceProvider)
       {
           if (_enumType == null)
           {
               throw new Exception("必须设置枚举类型");
           }
           var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
           var enumValues = Enum.GetValues(actualEnumType);
           if (actualEnumType == _enumType)
           {
               return enumValues;
           }
           var nullableEnumValues = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
           enumValues.CopyTo(nullableEnumValues, 1);
           return nullableEnumValues;
       }
   }
相关推荐
dalong1014 小时前
WPF:3D正四面体自动旋转
3d·wpf
He BianGu15 小时前
【WPF-Control】二次开发总览
wpf
绿浪198418 小时前
WPF 后台刷新界面总结
wpf
绿浪19842 天前
WPF UI标准流水线
ui·wpf
心平气和量大福大2 天前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
绿浪19842 天前
WPF 防重入,时序错乱详解
wpf
whn19773 天前
oracle的节点2无法启动asm实例 提示PMON terminating the instance due to error 481
数据库·oracle·wpf
完美火龙篇 四月的友3 天前
WPF 笔迹延迟优化从硬件到软件的全链路分析
wpf
dalong103 天前
WPF:3D立方体
3d·wpf
Xin_ye100864 天前
第三章:内存泄漏的常见“案发现场”
c#·wpf