如何将对象转换为转换器中的int?

时间:2009-05-27 12:29:15

标签: c# wpf converter

我放弃了,我该如何投这个?

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;
    }
}

6 个答案:

答案 0 :(得分:3)

Convert.ToInt32Int32.Parse都应该有效...如果不这样做,则该值绝对不是int;)
尝试在转换器中设置一个断点来观察值,它可能会告诉你为什么它不起作用

答案 1 :(得分:2)

如果该值实际上是一个字符串对象(内容表示一个整数值),则会产生最小的开销:

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

Convert.ToInt32应该能够处理大多数可能转换为int的内容,例如包含数字或任何数字类型的字符串,其范围在int之内可以处理。

答案 2 :(得分:0)

在Convert方法的左括号处放置断点。以调试模式启动应用程序。当遇到断点时,分析的实际类型。做演员。如果value是字符串,则将其转换为字符串,然后解析结果以获取整数。再次运行该程序。这次应该可以工作。

答案 3 :(得分:0)

如果值是对象,则ToString()最好在解析为Int int amount = Int32.Parse(value.ToString());之前转换为字符串

答案 4 :(得分:0)

答案基本上很简单。因为--- title: "My title" author: "Me" date: May 2018 output: pdf_document --- # Introduction Some text. 本身有一个称为IValueConverter的方法,所以不能像这样简单地使用Convert对象。

但是,如果添加正确的前缀,它将起作用:

Convert

答案 5 :(得分:0)

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

我认为这是最安全的方法!

相关问题