Reputation: 126
I am trying to set up an IValueConverter in WPF, C#. The purpose of this converter is to take the value that is passed in and divide by 100 so that we can get a double. I don't see any error's in then code before launching, but when I go to test it, i get the following error:
System.InvalidCastException: 'Specified cast is not valid.'
Here is the code for the converter:
public class DecimalPlace : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToDouble(value) / 100.00;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I am unsure as to why I am unable to cast value as a double to do the required math
This is where I am calling it:
<DataGridTextColumn Header="Price" Width="2*" Binding="{Binding intPrice, Converter={StaticResource DecimalPlace}, StringFormat='{}{0:C0}'}"/>
Upvotes: 1
Views: 1511
Reputation: 3816
Another variant, more resilient to missing validation.
public class DecimalPlace : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double parsed=0;
if (!double.TryParse(out parsed))
return parsed;
return (parsed) / 100.00;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
double parsed=0;
if (!double.TryParse(out parsed))
return parsed;
return System.Convert.ToInt32(parsed) * 100;
}
}
Upvotes: 0
Reputation: 3033
My guess is that targetType is string
and the exception isn't actually occurring in your code (you neglected to post the stacktrace). It's being bound to a DataGridTextColumn
which needs a string. So your converter must return a string. Normally WPF automatically handles converting between types like string
and double
in a binding when going from source to target and vice verse, but if you specify your own converter, you must make sure to provide exactly the correct return type.
The simple fix is:
public class DecimalPlace : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (System.Convert.ToDouble(value) / 100.00).ToString();
}
}
But if you want a more generic useful converter, you'll need to check targetType
and convert to the correct type (you can possibly use TypeDescriptor.GetConverter
Upvotes: 2
Reputation: 3816
Please include the Xaml where you use this converter. My guess is that you use the empty string initially in the textbox. Try to apply a fallback value to 0. You should check in the converter code that your input value can in fact be parsed to a number, using for example double.TryParse !
<TextBox Text=“{Binding MyNumberInViewModel, Mode=Twoway, Fallbackvalue=‘0’}” />
Upvotes: 0