You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
2.0 KiB
55 lines
2.0 KiB
using Humanizer;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.Windows.Data;
|
|
|
|
namespace MultiTerm.Wpf.ValueConverters;
|
|
|
|
/// <summary>
|
|
/// Can convert an enum value to a human readable string. Therefore it uses the Description attribute if set.
|
|
/// </summary>
|
|
[ValueConversion(typeof(Enum), typeof(Enum))]
|
|
public class EnumValueToEnumDescriptionConverter : IValueConverter
|
|
{
|
|
/// <summary>
|
|
/// Converts complete enum to <see cref="IEnumerable"/> of <see cref="string"/>.
|
|
/// Also converts single enum values to <see cref="string"/>.
|
|
/// </summary>
|
|
/// <returns>description or humanized string of the enum value</returns>
|
|
/// <exception cref="NotImplementedException">if <paramref name="value"/> is another type than an <see cref="IEnumerable"/> or <see cref="Enum"/></exception>
|
|
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
|
{
|
|
if(value is IEnumerable arrayOfEnumValues)
|
|
{
|
|
List<string> outputValues = new();
|
|
foreach (var item in arrayOfEnumValues)
|
|
{
|
|
outputValues.Add(((Enum)item).Humanize());
|
|
}
|
|
return outputValues;
|
|
}
|
|
else if(value is Enum)
|
|
{
|
|
return ((Enum)value).Humanize();
|
|
}
|
|
else
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts single string values to Enum of <paramref name="targetType"/>.
|
|
/// </summary>
|
|
/// <returns>enum value</returns>
|
|
/// <exception cref="ArgumentException">if value is not a string</exception>
|
|
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."); }
|
|
|
|
return stringValue.DehumanizeTo(targetType);
|
|
}
|
|
}
|
|
|