It is possible to create a converter between enum values and their underlying integral types in a reusable way -- that is, you don't need to define a new converter for each enum types. There's enough information provided to Convert
and ConvertBack
for this.
public sealed class BidirectionalEnumAndNumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
if (targetType.IsEnum)
{
// convert int to enum
return Enum.ToObject(targetType, value);
}
if (value.GetType().IsEnum)
{
// convert enum to int
return System.Convert.ChangeType(
value,
Enum.GetUnderlyingType(value.GetType()));
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// perform the same conversion in both directions
return Convert(value, targetType, parameter, culture);
}
}
When invoked, this converter flips the value's type between int/enum value based purely on the value
and targetType
values. There are no hard-coded enum types.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…