Bra*_*ipp 7 c# xamarin xamarin.forms
我创建了Entry,我试图将它绑定到Decimal属性,如下所示:
var downPayment = new Entry () {
HorizontalOptions = LayoutOptions.FillAndExpand,
Placeholder = "Down Payment",
Keyboard = Keyboard.Numeric
};
downPayment.SetBinding (Entry.TextProperty, "DownPayment");
Run Code Online (Sandbox Code Playgroud)
当我尝试在模拟器上输入Entry时,我收到以下错误.
对象类型System.String无法转换为目标类型:System.Decimal
Ste*_*oix 13
在撰写本文时,在绑定时没有内置转换(但这是有效的),因此绑定系统不知道如何将DownPayment
字段(小数)转换为Entry.Text
(字符串).
如果OneWay
绑定是您所期望的,字符串转换器将完成这项工作.这适用于Label
:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", stringFormat: "{0}"));
Run Code Online (Sandbox Code Playgroud)
对于a Entry
,您希望绑定在两个方向都有效,因此您需要一个转换器:
public class DecimalConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is decimal)
return value.ToString ();
return value;
}
public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
decimal dec;
if (decimal.TryParse (value as string, out dec))
return dec;
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在绑定中使用该转换器的实例:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));
Run Code Online (Sandbox Code Playgroud)
注意:
OP的代码应该在1.2.1及更高版本中开箱即用(来自Stephane对问题的评论).对于低于1.2.1的版本,这是一种解决方法