7

我已经创建了 Entry 并且我正在尝试将其绑定到 Decimal 属性,如下所示:

var downPayment = new Entry () {
    HorizontalOptions = LayoutOptions.FillAndExpand,
    Placeholder = "Down Payment",
    Keyboard = Keyboard.Numeric
};
downPayment.SetBinding (Entry.TextProperty, "DownPayment");

当我尝试在模拟器上输入条目时出现以下错误。

对象类型 System.String 无法转换为目标类型:System.Decimal

4

1 回答 1

14

在撰写本文时,绑定时没有内置转换(但这是可行的),因此绑定系统不知道如何将您的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 版本的解决方法

于 2014-06-27T09:42:10.987 回答