简体   繁体   English

如何将Xamarin.Forms条目绑定到非字符串类型,例如Decimal

[英]How to bind Xamarin.Forms Entry to a Non String Type such as Decimal

I have and Entry created and I am trying to bind it to a Decimal property like such: 我创建了Entry,我试图将它绑定到Decimal属性,如下所示:

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

I am getting the following error when I try to type into the Entry on the simulator. 当我尝试在模拟器上输入Entry时,我收到以下错误。

Object type System.String cannot be converted to target type: System.Decimal 对象类型System.String无法转换为目标类型:System.Decimal

At the time of this writing, there are no built-in conversion at binding time (but this is worked on), so the binding system does not know how to convert your DownPayment field (a decimal) to the Entry.Text (a string). 在撰写本文时,在绑定时没有内置转换(但这是有效的),因此绑定系统不知道如何将您的DownPayment字段(小数)转换为Entry.Text (一个字符串) )。

If OneWay binding is what you expect, a string converter will do the job. 如果OneWay绑定符合您的预期,则字符串转换器将完成此任务。 This would work well for a Label : 这适用于Label

downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", stringFormat: "{0}"));

For an Entry , you expect the binding to work in both direction, so for that you need a converter: 对于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;
    }
}

and you can now use an instance of that converter in your Binding: 现在,您可以在绑定中使用该转换器的实例:

downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));

NOTE: 注意:

OP's code should work out of the box in version 1.2.1 and above (from Stephane's comment on the Question). OP的代码应该在1.2.1及更高版本中开箱即用(来自Stephane对问题的评论)。 This is a workaround for versions lower than 1.2.1 对于低于1.2.1的版本,这是一种解决方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM