82 lines
2.3 KiB
C#
82 lines
2.3 KiB
C#
using System;
|
|
using System.Globalization;
|
|
using System.Linq;
|
|
using System.Windows.Data;
|
|
|
|
namespace BDU.Converters
|
|
{
|
|
public class EnumValueConverter : IMultiValueConverter
|
|
{
|
|
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
|
|
{
|
|
// 验证输入参数
|
|
if (values.Length < 2 || values[0] == null || values[1] == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
// 获取枚举类型
|
|
Type enumType = values[0] as Type;
|
|
if (enumType == null || !enumType.IsEnum)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
// 获取数值
|
|
object value = values[1];
|
|
|
|
// 确保数值类型匹配枚举的底层类型
|
|
Type underlyingType = Enum.GetUnderlyingType(enumType);
|
|
object convertedValue;
|
|
|
|
try
|
|
{
|
|
convertedValue = System.Convert.ChangeType(value, underlyingType);
|
|
}
|
|
catch
|
|
{
|
|
// 如果转换失败,尝试直接使用原始值
|
|
convertedValue = value;
|
|
}
|
|
|
|
// 将数值转换为枚举值
|
|
return Enum.ToObject(enumType, convertedValue);
|
|
}
|
|
catch
|
|
{
|
|
// 发生任何异常时返回null
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
|
|
{
|
|
if (value == null)
|
|
{
|
|
return [null, null];
|
|
}
|
|
|
|
try
|
|
{
|
|
// 获取枚举值的底层数值
|
|
Type enumType = value.GetType();
|
|
if (!enumType.IsEnum)
|
|
{
|
|
return [null, null];
|
|
}
|
|
|
|
Type underlyingType = Enum.GetUnderlyingType(enumType);
|
|
object numericValue = System.Convert.ChangeType(value, underlyingType);
|
|
|
|
// 返回枚举类型和对应的数值
|
|
return [enumType, numericValue];
|
|
}
|
|
catch
|
|
{
|
|
return [null, null];
|
|
}
|
|
}
|
|
}
|
|
} |