Reputation: 3585
I have an IValueConverter
which I want to use for doing simple math that has the following Convert
function :
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if (parameter == null)
{
return value;
}
switch (((string)parameter).ToCharArray()[0])
{
case '%':
return (double)value % double.Parse(
((string)parameter).TrimStart(new char[] {'%'}));
case '*':
return (double)value * double.Parse(
((string)parameter).TrimStart(new char[] {'*'}));
case '/':
return (double)value / double.Parse(
((string)parameter).TrimStart(new char[] {'/'}));
case '+':
return (double)value + double.Parse(
((string)parameter).TrimStart(new char[] {'+'}));
case '-':
if (((string)parameter).Length > 1)
{
return (double)value - double.Parse(
((string)parameter).TrimStart(new char[] {'-'}));
}
else
{
return (double)value * -1.0D;
}
default:
return DependencyProperty.UnsetValue;
}
}
Obviously this doesn't work for each case because some properties are of type int
.
I know that the targetType
parameter is likely what I need to use in this converter but I have found no examples of how to make proper use of it to convert the return value to what it needs to be accordingly.
Does anyone know how to use the targetType
parameter in this context?
Upvotes: 7
Views: 3270
Reputation: 128061
This should work without too much overhead:
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
double result = ... // your math
return System.Convert.ChangeType(result, targetType);
}
Upvotes: 8
Reputation: 2246
you can do this
var typeCode = Type.GetTypeCode(targetType); // Pass in your target type
if(typeCode == TypeCode.Int32)
{
// it is int type
}
Upvotes: 2