如何将Xamarin.Forms条目绑定到非字符串类型(如Decimal) [英] How to bind Xamarin.Forms Entry to a Non String Type such as Decimal
问题描述
我已经创建了Entry,并且正在尝试将其绑定到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");
当我尝试在模拟器上键入Entry时,出现以下错误.
I am getting the following error when I try to type into the Entry on the simulator.
对象类型System.String无法转换为目标类型:System.Decimal
Object type System.String cannot be converted to target type: System.Decimal
推荐答案
在撰写本文时,在绑定时没有内置的转换(但是可以进行此操作),因此绑定系统不知道如何将您的DownPayment
字段(十进制)转换为Entry.Text
(字符串).
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).
如果您希望使用OneWay
绑定,则将使用字符串转换器完成此工作.这对于Label
:
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}"));
对于Entry
,您希望绑定在两个方向上都有效,因此您需要一个转换器:
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;
}
}
现在您可以在Binding中使用该转换器的实例:
and you can now use an instance of that converter in your Binding:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));
注意:
OP的代码应该在1.2.1及更高版本中开箱即用(来自Stephane对问题的评论).对于低于1.2.1的版本,这是一种解决方法
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
这篇关于如何将Xamarin.Forms条目绑定到非字符串类型(如Decimal)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!