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