我已经创建了 Entry,我正在尝试将它绑定(bind)到像这样的 Decimal 属性:
var downPayment = new Entry () {
HorizontalOptions = LayoutOptions.FillAndExpand,
Placeholder = "Down Payment",
Keyboard = Keyboard.Numeric
};
downPayment.SetBinding (Entry.TextProperty, "DownPayment");
当我尝试在模拟器上输入 Entry 时出现以下错误。
Object type System.String cannot be converted to target type: System.Decimal
最佳答案
在撰写本文时,绑定(bind)时没有内置转换(但这已经完成),因此绑定(bind)系统不知道如何转换您的 DownPayment
字段(a十进制)到 Entry.Text
(一个字符串)。
如果 OneWay
绑定(bind)是您所期望的,字符串转换器将完成这项工作。这适用于 Label
:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", stringFormat: "{0}"));
对于 Entry
,您希望绑定(bind)可以双向工作,因此您需要一个转换器:
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;
}
}
现在您可以在您的绑定(bind)中使用该转换器的一个实例:
downPayment.SetBinding (Entry.TextProperty, new Binding ("DownPayment", converter: new DecimalConverter()));
注意:
OP 的代码应该在 1.2.1 及更高版本中开箱即用(来自 Stephane 对问题的评论)。这是低于 1.2.1 版本的解决方法
关于c# - 如何将 Xamarin.Forms 条目绑定(bind)到非字符串类型,例如 Decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24442617/