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

前端 未结 1 1320
滥情空心
滥情空心 2021-02-09 06:20

I have and Entry created and I am trying to bind it to a Decimal property like such:

var downPayment = new Entry () {
            


        
相关标签:
1条回答
  • 2021-02-09 06:53

    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

    0 讨论(0)
提交回复
热议问题