条目绑定到int?在Xamarin表格中

时间:2017-03-09 15:48:00

标签: xamarin binding xamarin.forms

我在Xamarin Forms中有一个简单的条目:

<Entry Text="{Binding Number, Mode=TwoWay}" Placeholder="Number" Keyboard="Numeric" />

在ViewModel中有属性:

    private int? _number;
    public int? Number
    {
        get { return _number; }
        set
        {
            if (SetProperty(ref _number, value))
            {
                OnPropertyChange(nameof(Number));
            }
        }
    }

我在Entry中输入数字并按下按钮,但在按钮单击过程中 - 数字仍为空。我做错了什么?

2 个答案:

答案 0 :(得分:16)

您可以将int绑定到Entry ,但您不能绑定可以为null的int。您可以添加另一个将数字转换为字符串的属性,也可以轻松创建像这样的值转换器...

class NullableIntConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var nullable = value as int?;
        var result = string.Empty;

        if (nullable.HasValue)
        {
            result = nullable.Value.ToString();
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var stringValue = value as string;
        int intValue;
        int? result = null;

        if (int.TryParse(stringValue, out intValue))
        {
            result = new Nullable<int>(intValue);
        }

        return result;
    }

...并在您的页面中使用它......就像这样......

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:IntBinding"
             x:Class="IntBinding.DemoPage">

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:NullableIntConverter x:Key="NullableIntConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout>
        <Entry Text="{Binding Number, Mode=TwoWay, Converter={StaticResource NullableIntConverter}}" Placeholder="Number" Keyboard="Numeric" />
        <Label Text="{Binding Number, Converter={StaticResource NullableIntConverter}}" />
    </StackLayout>
</ContentPage>

答案 1 :(得分:11)

条目接受一个字符串。如果你想绑定一个int属性你应该使用IValueConverter但我认为最好的解决方案是使用String属性而不是将值从String转换为Int

public string StrNumber{
   get {
        if (Number == null) 
            return "";
        else
            return Number.ToString();
   }

   set {
       try {
           Number = int.Parse(value);
       }
       catch{
           Number = null;
       }
   }
}