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;
       }
   }
相关推荐
Chris _data1 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头2 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf
步步为营DotNet2 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
芒鸽2 天前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology2 天前
Flink状态管理与容错(二)
大数据·flink·wpf
happyprince3 天前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com3 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
小满Autumn3 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
政沅同学4 天前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
happyprince4 天前
03_verl-设计理念与核心原理
wpf