Question

I give up, how do I cast this?

class AmountIsTooHighConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //int amount = (int)value;
        //int amount = (int)(string)value;
        //int amount = (int)(value.ToString);
        //int amount = Int32.Parse(value);
        //int amount = (int)Convert.ChangeType(value, typeof(int));
        //int amount = Convert.ToInt32(value);
        if (amount >= 35)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
Was it helpful?

Solution

Both Convert.ToInt32 or Int32.Parse should work... If they don't, then the value is definitely not an int ;)
Try to put a breakpoint in your converter to watch the value, it might show you why it doesn't work

OTHER TIPS

If the value is actually a string object (with a content that represents an integer value), this gives the least overhead:

int amount = Int32.Parse((string)value);

The Convert.ToInt32 should be able to handle most anything that is possible to convert to an int, like a string containing digits or any numeric type that is within the range that an int can handle.

Put a breakpoint at the opening parenthesis of your Convert method. Start your application in debug mode. When the breakpoint is hit analyze the actual type of value. Do the cast. If value is string cast it to string and then parse the result to get an integer. Run the program again. It should work this time.

If the value is an object, ToString() is better to convert to string before parsing to Int int amount = Int32.Parse(value.ToString());

The answer is basically simple. Because the IValueConverter has itself a method called Convert you cannot simply us the Convert object just like that.

But if you add the correct prefix it works:

int amount = System.Convert.ToInt32(value);
int amount;
if(int32.TryParse((string)value,out amount)
{
   if(amount>=35)
    {
        return true;
    }
    else
    {
      return false;
    }
}
else
{
  return false;
}

This is safest way, I think!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top