Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entry binding to int? in Xamarin Forms

I have a simple entry in Xamarin Forms:

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

In ViewModel there is property:

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

I enter number in Entry and press button, but in button clicked procedure - Number is still null. What am I doing wrong?

like image 970
Uros Avatar asked Mar 09 '17 15:03

Uros


1 Answers

You can bind an int to an Entry but you can't bind a nullable int. You can either add another property which converts the number to a string, or you can easily create a value converter like this...

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;
    }

... and use it in your page like this...

<?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>
like image 128
Martynnw Avatar answered Oct 02 '22 11:10

Martynnw