Multiprocotol Terminalprogram (BAT)
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.
MultiTerm/MultiTerm.Wpf/ValueConverters/EnumValueToEnumDescriptionC...

63 lines
2.4 KiB

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using Common.Helpers;
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(EnumHelpers.GetEnumDescription((Enum)item));
}
return outputValues;
}
else if(value is Enum)
{
return EnumHelpers.GetEnumDescription((Enum)value);
}
else
{
throw new NotImplementedException();
}
}
/// <summary>
/// Converts single string values to Enum of <paramref name="targetType"/>.
/// </summary>
/// <returns>enum value or empty object if no matching enum value was found</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."); }
// 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;
}
}