定义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;
-
-
- }
- }
应用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
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频