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;
       }
   }
相关推荐
她说彩礼65万2 小时前
WPF TemplateBinding
wpf
她说彩礼65万3 小时前
WPF 三大模板类型 四大属性名称
wpf
无心水3 小时前
金融系统数据一致性之战:联机交易与批量作业的冲突处理完全指南
人工智能·金融·wpf·批量作业·顶尖架构师·联机交易·金融架构师
步步为营DotNet1 天前
深入.NET 11:ASP.NET Core 10 在构建高可用分布式系统的关键技术与实践
asp.net·.net·wpf
lingxiao168882 天前
智慧停车场(SmartParking)
c#·自动化·wpf
战族狼魂2 天前
上位机软件开发完整学习路线与项目实战指南
单片机·c#·wpf
500843 天前
昇腾 CANN 的五层架构,到底分了哪五层
java·人工智能·分布式·架构·ocr·wpf
醉颜凉3 天前
ZooKeeper Zxid 与 Epoch 深度解析:分布式事务的时空坐标
分布式·zookeeper·wpf
500843 天前
HCCL 集合通信编程:多卡协同的正确姿势
java·flutter·性能优化·electron·wpf