I want to create a dynamic 2-way-converter for all possible enums in my application.
I don’t want to have to create a converter for each enum, I want to create one converter that provides converting from enum to byte and from byte to enum vice versa.
How can I get there? My approach is already 2-way but requires a static cast (MyEnum) in the code:
public class MyEnumConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) {
return (MyEnum)value;
}
public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) {
return (byte)value;
}
public override object ProvideValue(System.IServiceProvider serviceProvider) {
return this;
}
}
I believe you can do this 2 different ways.
Option 1: Take advantage of the
targetTypeparameter on the convert methods. When you need to convert to the enum, thentargetTypeis the enum type. You can use one of the static methods on theSystem.Enumclass to do the conversion.Option 2: In your xaml, use the ConverterParameter to pass in the enum type you want to convert to:
If you go that route, then the type will be in the
parameterparameter of the convert methods. Again, the static methods on theSystem.Enumclass will do the heavy lifting for you.