c# - 如何将 Xamarin.Forms 条目绑定(bind)到非字符串类型,例如 Decimal

标签 c# xamarin xamarin.forms

我已经创建了 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/

相关文章:

c# - Unable install Xamarin Firebase - Common 32.961.0 to xamarin.forms解决方法

c# - 检查 HttpStatusCode 是否表示成功或失败

c# - 如何修复 int.Parse 中的 ArgumentNullException?

Xamarin Forms 选择器的默认值

C# 将 XML 解析为不同的列表

ios - DisplayAlert 仅在 Xamarin 表单 ios 上不显示

c# - 需要获取多个列表的所有组合,从每个列表中获取集合金额

c# - 为什么这个对象在浅拷贝后不为空?

c# - 方法 X 不支持转换为 SQL - bool 值和日期时间

c# - 为什么我会收到此错误?无法从中加载类型