在撰写本文时,绑定时没有内置转换(但这是可行的),因此绑定系统不知道如何将您的DownPayment
字段(十进制)转换为Entry.Text
(字符串)。
如果OneWay
绑定是您所期望的,那么字符串转换器将完成这项工作。这适用于Label
:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", stringFormat: "{0}"));
对于 an 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;
}
}
现在您可以在 Binding 中使用该转换器的实例:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));
笔记:
OP 的代码应该在 1.2.1 及更高版本中开箱即用(来自 Stephane 对问题的评论)。这是低于 1.2.1 版本的解决方法