Reputation: 842
Is it possible to use a converter the "wrong" way around? In other words: can I swap source and target?
Here's an example:
I created a simple IValueConverter
called NullableDecimalToStringConverter
which converts an input "NULL" into null and a number into decimal.
I use it to bind a TextBox in my WPF view to a decimal? property in my ViewModel.
In another context I'd like to convert a NullableDecimal into a String in the same way...
Is it possible to simply use the existing NullableDecimalToStringConverter
inverted?
One method is to use the parameter of the converter to tell the converter which way it should convert.
But is there a .NET build in way to do such a thing?
Another way would be to build a base class with both conversion methods and two separate converter which call the base class methods...
Upvotes: 1
Views: 420
Reputation: 399
I'm not sure exactly what you're trying to target in terms of functionality, but have you considered an extension method that extends String? You could then utilize this on your getter and setter in your viewmodel (assuming you're using MVVM). Here's an example of what I'm talking about:
public static class Extensions
{
public static decimal? ToSafeNullDecimal(this string value)
{
decimal? dec = null;
if (string.IsNullOrWhiteSpace(value)) return null;
decimal x;
if (decimal.TryParse(value, out x))
dec = x;
return dec;
}
}
Upvotes: 0
Reputation: 244757
You could create a converter that reverses the direction, something like:
[ContentProperty("Converter")]
public class ReverseConverter : IValueConverter
{
public IValueConverter Converter { get; set; }
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return Converter.ConvertBack(value, targetType, parameter, culture);
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
return Converter.Convert(value, targetType, parameter, culture);
}
}
Usage in XAML would then look like this:
<local:ReverseConverter>
<!-- put the other converter here -->
</local:ReverseConverter>
Upvotes: 3