using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Windows.Data; using Common.Helpers; namespace MultiTerm.Wpf.ValueConverters; /// /// Can convert an enum value to a human readable string. Therefore it uses the Description attribute if set. /// [ValueConversion(typeof(Enum), typeof(Enum))] public class EnumValueToEnumDescriptionConverter : IValueConverter { /// /// Converts complete enum to of . /// Also converts single enum values to . /// /// description or humanized string of the enum value /// if is another type than an or public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(value is IEnumerable arrayOfEnumValues) { List outputValues = new(); foreach (var item in arrayOfEnumValues) { outputValues.Add(EnumHelpers.GetEnumDescription((Enum)item)); } return outputValues; } else if(value is Enum) { return EnumHelpers.GetEnumDescription((Enum)value); } else { throw new NotImplementedException(); } } /// /// Converts single string values to Enum of . /// /// enum value or empty object if no matching enum value was found /// if value is not a string public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // guard that it is a string, cannot be a collection if (value is not string stringValue) { throw new ArgumentException("Can only convert string values."); } // find value by description var objOfEnumType = EnumHelpers.CreateInstanceOfEnumType(targetType); var enumObjectWithMatchingDescription = EnumHelpers.GetEnumValueByDescription(objOfEnumType, stringValue); // return new object if none found if(enumObjectWithMatchingDescription == null) { return new object(); } return enumObjectWithMatchingDescription; } }