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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With