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;
       }
   }
相关推荐
SamChan9011 小时前
FastAPI+Celery+Redis搭建企业级PDF翻译异步任务系统
redis·后端·python·pdf·wpf·fastapi
李高钢12 小时前
C# WPF Prism 进阶(三):导航(Navigation)深入
开发语言·c#·wpf
李高钢1 天前
C# WPF 的 Prism 框架入门:核心概念与一个完整示例
开发语言·c#·wpf
SamChan901 天前
用Playwright端到端测试PDF翻译功能:Web自动化测试实战
前端·python·ai·pdf·wpf
Now喔2 天前
WPF动画
wpf
FuckPatience3 天前
WPF 给一个界面上的按钮应用同一种样式
wpf
Polevne5 天前
WPF\MAUI\Avalonia Dispatcher
wpf
Ares-Wang5 天前
wpf 图表制作 LiveCharts
wpf
A_nanda5 天前
c#WPF开发常见问题
开发语言·c#·wpf
Wang's Blog7 天前
AI Agent白手起家60: 多智能体架构解析与 LangGraph 入门
人工智能·架构·wpf