Code Snippet
- public class TranslateEnumConverter : MarkupExtension, IValueConverter
- {
- public static TranslateEnumConverter _converter = null;
- public TranslateEnumConverter()
- {
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- public override object ProvideValue(IServiceProvider serviceProvider)
- {
- if (_converter == null)
- {
- _converter = new TranslateEnumConverter();
- }
- return _converter;
- }
- }
Let's start with nearly ordinary Converter class above. What's a bit different is using MarkupExtension as one of the ways to allow adding converter to binding in XAML without the need of declaring it as a resource. The pretty straightforward use of ProvideValue allows us exactly this:
Converter={Converters:TranslateEnumConverter}
Converters is the namespace where all our converters reside.
The Convert method, as in any converter, returns the converted value from VM to View. In our case it gets the resource and the translated string of the enum and returns it.
Code Snippet
- public object Convert(object value, Type targetType,
- object parameter, System.Globalization.CultureInfo culture)
- {
- if (value == null)
- return String.Empty;
- if (parameter == null)
- throw new ArgumentNullException("parameter");
- String inputParam = parameter.ToString();
- String resourceName = String.Empty;
- resourceName = parameter.ToString();
- Type type = Type.GetType(resourceName);
- string name = value.ToString();
- if (type == null) // Invalid resource name
- throw new ArgumentException("Resource name
- should be a fully qualified name");
- var property = type.GetProperty(name, BindingFlags.Static |
- BindingFlags.Public | BindingFlags.NonPublic);
- string translation = string.Empty;
- if (property == null) // With no corresponding Resx translation, there's an error message displayed
- translation = String.Format("Field {0} not found in the resource file {1}", name, resourceName);
- else
- translation = property.GetValue(null, null).ToString();
- return translation;
- }
You can read the previous post's description to gain more knowledge about how the resource name is passed into the converter and parsed into parameters - beside that the code above should be pretty self-explanatory. With the code we've got we can call the converter from XAML, with Status being the Enum property from the ViewModel and fully qualified name of the resource class as the ConverterParameter:
Binding="{Binding Status,
Converter={Converters:TranslateEnumConverter},
ConverterParameter='Mod.Ule.Resources.Enums.EnumStrings,Mod.Ule'}"