EnumDataProvider support for Attributes

This commit is contained in:
chenjie02_cd committed 2021-09-06 20:10:07 +08:00
1 parent 4d7697914f
commit f6f167221d
3 files changed
+69 -2

No files matched your search

@@ -1,10 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
namespace HandyControl.Data
{
public class EnumDataProvider : ObjectDataProvider
{
public EnumDataProvider()
{
MethodName = nameof(GetValues);
ObjectType = typeof(System.Enum);
}
private Type _type;
public Type Type
{
@@ -12,10 +20,59 @@ namespace HandyControl.Data
set
{
_type = value;
MethodName = "GetValues";
ObjectType = typeof(System.Enum);
MethodParameters.Add(value);
}
}
private bool _useAttributes;
public bool UseAttributes
{
get => _useAttributes;
set
{
_useAttributes = value;
ObjectType = value ? typeof(EnumDataProvider) : typeof(System.Enum);
}
}
public static IEnumerable<EnumItem> GetValues(Type enumType)
{
if (enumType == null)
{
throw new ArgumentNullException(nameof(enumType));
}
var resultList = new List<EnumItem>();
var values = System.Enum.GetValues(enumType);
foreach (System.Enum value in values)
{
var fieldInfo = enumType.GetField(value.ToString());
if (fieldInfo == null)
{
continue;
}
if (fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), true) is BrowsableAttribute[] { Length: > 0 } browsableAttributes)
{
if (!browsableAttributes[0].Browsable)
{
continue;
}
}
if (fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true) is DescriptionAttribute[] { Length: > 0 } descriptionAttributes)
{
resultList.Add(new EnumItem
{
Description = descriptionAttributes[0].Description,
Value = value
});
}
}
return resultList;
}
}
}
@@ -0,0 +1,9 @@
namespace HandyControl.Data
{
public class EnumItem
{
public string Description { get; set; }
public System.Enum Value { get; set; }
}
}
@@ -83,6 +83,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Controls\Tag\TagContainer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Controls\Text\SimpleText.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Controls\Window\GlowWindow.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Data\EnumItem.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Tools\Converter\BooleanArr2BooleanConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Tools\Generator\DateTimeRangeComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Data\Enum\VisualWrapping.cs" />