【发布时间】:2018-07-11 19:33:59
【问题描述】:
我正在尝试在 WPF、C# 中设置 IValueConverter。这个转换器的目的是把传入的值除以 100,这样我们就可以得到一个 double。在启动之前我没有看到代码中有任何错误,但是当我去测试它时,我收到以下错误:
System.InvalidCastException: '指定的强制转换无效。'
这是转换器的代码:
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();
}
}
- 值 = 5
- targetType = {Name = "String" FullName = "System.String"}
我不确定为什么我无法将 value 转换为 double 来进行所需的数学运算
这就是我所说的:
<DataGridTextColumn Header="Price" Width="2*" Binding="{Binding intPrice, Converter={StaticResource DecimalPlace}, StringFormat='{}{0:C0}'}"/>
【问题讨论】:
-
它是否试图将 .05 之类的转换为整数?
-
Tbh,我什至还没到那部分。从理论上讲,这就是代码会做的事情并且会严重破坏。我的问题是将 value(5) 转换为 double 然后除以 100 得到 0.05
-
您的函数返回
object。您需要返回Double和Int32才能使转换在您的return语句中有效。 -
哪一行抛出异常?什么是目标类型?绑定是什么样子的?
-
啊,就是这样 return double
标签: c# wpf ivalueconverter