using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using System;
using System.Reflection;
namespace ModbusDemo.Extension
{
///
/// 此处代码是复制粘贴,用来让枚举类型绑定到下拉框上
///
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 ArgumentException("Type must be for an Enum.");
}
_enumType = value;
}
}
}
public EnumBindingSourceExtension() { }
public EnumBindingSourceExtension(Type enumType)
{
EnumType = enumType;
}
///
/// 将枚举转换为数组,返回出去
/// 可以绑定可空枚举
///
/// xmal上下文
///
///
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_enumType == null)
throw new InvalidOperationException("The EnumType must be specified.");
var actualEnumType = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
var enumValues = Enum.GetValues(actualEnumType);
if (actualEnumType == _enumType)
return enumValues;
var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1);
enumValues.CopyTo(tempArray, 1);
return tempArray;
}
}
}