JD2022-TU1/main/tools/framework/JD.WPF/Converters/EnumToStringConverter.cs

26 lines
1.1 KiB
C#

using System;
using System.Windows.Data;
namespace JD.WPF.Converters
{
public class EnumToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is Enum))
throw new NotSupportedException("This converter only supports Enum values. ");
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is string))
throw new NotSupportedException("This converter only supports string values for reverse conversions. ");
if (!(parameter is Type) || !((Type)parameter).IsEnum)
throw new InvalidOperationException("An enum type must be provided as parameter to proceed to a reverse conversion from a string value. ");
Type enumType = (Type)parameter;
return Enum.Parse(enumType, (string)value, true);
}
}
}