/////////////////////////////////////////////////////////////////////////////// //Copyright (c) 2016, 北京探索者软件公司 //All rights reserved. //文件名称: EnumToEnumItemConverter.cs //文件描述: 枚举向枚举条目对象转换 //创 建 者: xls //创建日期: 2018-1-23 //版 本 号:1.0.0.0 //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using FWindSoft.SystemExtensions; namespace FWindSoft.Wpf { public class EnumToEnumItemConverter : IValueConverter { public static EnumToEnumItemConverter Instance = new EnumToEnumItemConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Type sourceType = value.GetType(); if (!sourceType.IsEnum) return value; var enumerable = parameter as IEnumerable; if (enumerable == null) return value; if (targetType.GetGenericTypeDefinition().FullName!=typeof (EnumItem<>).FullName) { return value; } var anyItem = enumerable.FirstOrDefault(); if (anyItem == null) { return value; } var anyType = anyItem.GetType(); if (!anyType.IsGenericType) { return value; } if (anyType.GetGenericArguments()[0] != sourceType) { return value; } var property=anyType.GetProperty("Item", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (property == null) { return value; } foreach (var o in enumerable) { if ( System.Convert.ChangeType(property.GetValue(0), sourceType) .Equals(System.Convert.ChangeType(value, sourceType))) { return o; } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var anyType = value.GetType(); if (!anyType.IsGenericType) { return value; } if (anyType.GetGenericArguments()[0] != targetType) { return value; } var property = anyType.GetProperty("Item", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (property == null) { return value; } return System.Convert.ChangeType(property.GetValue(value), targetType); } } }