| 123456789101112131415161718192021222324252627282930313233343536373839 |
- using System;
- using System.ComponentModel;
- using System.Globalization;
- using System.Reflection;
- using System.Windows.Data;
- namespace TeamAAS.Converters
- {
- public class EnumDescriptionConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value == null) return null;
- var type = value.GetType();
- if (!type.IsEnum) return value;
- var field = type.GetField(value.ToString());
- if (field == null) return value;
- var attr = field.GetCustomAttribute<DescriptionAttribute>();
- return attr?.Description ?? value.ToString();
- }
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value == null) return Binding.DoNothing;
- if (!targetType.IsEnum) return Binding.DoNothing;
- foreach (var field in targetType.GetFields(BindingFlags.Public | BindingFlags.Static))
- {
- var attr = field.GetCustomAttribute<DescriptionAttribute>();
- if (attr != null && attr.Description == value.ToString())
- return field.GetValue(null);
- }
- try { return Enum.Parse(targetType, value.ToString()); }
- catch { return Binding.DoNothing; }
- }
- }
- }
|