【问题标题】:PlaceholderProperty bindingPlaceholder 属性绑定
【发布时间】:2016-01-28 04:31:08
【问题描述】:

我有一个视图,有两个基本字段,分别命名为 ID 和 Name,这些字段的 TextProperty 绑定到我的 ViewModel,使用 StudentID.SetBinding(Entry.TextProperty, new Binding("StudentID"));

学生 ID 是 int。在视图中,我为这些字段制作了占位符。但是,int 字段默认设置为 0。因此,当页面加载时,int 字段的占位符始终为 0。

如何绑定int字段的PlaceholderProperty?我正在使用 MVVMCross 和 Xamarin.Forms。

注意:我在视图定义中使用的是 C# 而不是 XAML 代码。

【问题讨论】:

  • 没有Entry.PlaceholderProperty 属性吗?
  • 是的,有一个,但我不确定我所做的是否正确,查看:StudentID.SetBinding(Entry.PlaceholderProperty, new Binding("StudentIDPlaceHolder")); ViewModel:私有字符串_SIDPH;公共字符串 StudentIDPlaceHolder { 获取 { 返回 _SIDPH; } 设置 { _SIDPH = "ID"; } } 这没有帮助。
  • 所以只是为了理解,您希望占位符显示一些文本?即..Enter number?
  • 完全正确!!但由于 TextProperty 已绑定,我的输入字段上显示为“0”。
  • 嗯,您可能希望将您的 id 设为可为空的 int,这样默认值为空。或者可能创建一个转换器,检查值是否为 0,然后返回 null。

标签: mvvmcross xamarin.forms


【解决方案1】:

将绑定更改为

StudentID.SetBinding(Entry.TextProperty, new Binding(path: "StudentID", converter: new IntToStringConverter()));

并创建一个转换器

public class IntToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((int)value) == 0) ? null : ((int)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int retVal;
        if(!(Int.TryParse((string)value, retVal)) retVal = 0;
        return retVal;
    }
}

这样,如果您的 int 为 0,则该值将作为 null 传递,但任何其他值都将正确传递。当条目的文本值为 null 时,会显示占位符文本,因此您只需执行 StudentID.Placeholder = "Enter student ID"; 即可,直到输入数字为止。转换器中的字符串验证非常基础,绝对可以改进。

【讨论】:

  • 这段代码有2个问题:1.tryparse需要out关键字2.条件表达式的类型无法确定,因为''和'int'之间没有隐式转换,不知道如何摆脱他们。
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 2014-05-01
  • 2011-02-22
  • 2011-06-20
  • 2010-11-26
  • 1970-01-01
  • 2014-02-12
相关资源
最近更新 更多