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;
       }
   }
相关推荐
斯文的八宝粥3 小时前
WPF企业内训全程实录(下)
大数据·hadoop·wpf
精明的身影2 天前
深入WPF -- Dispatcher(补)
wpf
云中飞鸿3 天前
该如何进行WPF界面设计
wpf
云中飞鸿4 天前
WPF分哪几块
wpf
newbe365245 天前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf
Chris _data22 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头23 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf
步步为营DotNet23 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
芒鸽23 天前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology23 天前
Flink状态管理与容错(二)
大数据·flink·wpf