You can bind int to a record, but you cannot bind null with int. You can add another property that 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 on 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>
source share