示例:WPF中绑定枚举到ComboBox的方式

发布于:2024-06-18 ⋅ 阅读:(78) ⋅ 点赞:(0)

一、目的:在开发过程中,经常会需要把枚举绑定到ComboxBox下拉列表中,其实方法有很多,这里面通过MarkupExtension扩展GetEnumSourceExtension去绑定到列表


二、实现

定义GetEnumSourceExtension类

    public class GetEnumSourceExtension : System.Windows.Markup.MarkupExtension
    {
        private Type _enumType;

        public Type EnumType
        {
            get { return this._enumType; }
            set
            {
                if (value != this._enumType)
                {
                    if (null != value)
                    {
                        Type enumType = Nullable.GetUnderlyingType(value) ?? value;

                        if (!enumType.IsEnum)
                            throw new ArgumentException("Type must be for an Enum.");
                    }
                    this._enumType = value;
                }
            }
        }

        public GetEnumSourceExtension()
        {

        }

        public GetEnumSourceExtension(Type enumType)
        {
            this.EnumType = enumType;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (null == this._enumType)
                throw new InvalidOperationException("This EnumType must be specified.");
            Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType;
            Array enumVlues = Enum.GetValues(actualEnumType);

            if (actualEnumType == this._enumType)
                return enumVlues;

            Array tempArray = Array.CreateInstance(actualEnumType, enumVlues.Length + 1);

            enumVlues.CopyTo(tempArray, 1);

            return tempArray;


        }
    }

三、环境


VS2022

四、示例

应用GetEnumSourceExtension扩展绑定到ComboBox数据源

<ComboBox ItemsSource="{h:GetEnumSource EnumType={x:Type HorizontalAlignment}}"/>

 显示效果

五、需要了解的知识点

MarkupExtension 类 (System.Windows.Markup) | Microsoft Learn 

六、源码地址

GitHub - HeBianGu/WPF-ControlDemo: 示例

GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库

GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库

七、了解更多

System.Windows.Controls 命名空间 | Microsoft Learn

https://github.com/HeBianGu

HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频


网站公告

今日签到

点亮在社区的每一天
去签到