How to associate a Xamarin.Forms record with a Non String type, such as Decimal

I have Entry created, and I'm trying to bind it to the Decimal property, for example:

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

I get the following error when I try to enter into Entry on the simulator.

The type of the System.String object cannot be converted to the target type: System.Decimal

+7
c # xamarin xamarin.forms
source share
1 answer

At the time of this writing, there is no built-in conversion during the binding (but this works), so the binding system does not know how to convert your DownPayment field (decimal) to Entry.Text (string).

If OneWay binding is what you expect, the string converter will do the job. This will work well for Label :

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

For Entry you expect the binding to work in both directions, so for this 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 now you can use an instance of this converter in your Binding:

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

Note:

OP code should work out of the box in versions 1.2.1 and higher (from Stephen’s comment on the Question). This is a workaround for versions below 1.2.1

+13
source share

All Articles