Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

Object type System.String cannot be converted to target type: System.Decimal

like image 573
Brandon Tripp Avatar asked Jun 27 '14 01:06

Brandon Tripp


1 Answers

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).

If OneWay binding is what you expect, a string converter will do the job. This would work well for a 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:

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). This is a workaround for versions lower than 1.2.1

like image 178
Stephane Delcroix Avatar answered Nov 04 '22 20:11

Stephane Delcroix