Entry binding to int? in Xamarin formats

I have a simple entry in Xamarin Forms:

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

ViewModel has a property:

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

I enter the number in the input field and press the button, but in the procedure with the button pressed - the number is still zero. What am I doing wrong?

+5
source share
2 answers

Input takes a string. If you want to bind the int property, you should use an IValueConverter , but I believe that a better solution is to use the String property than converting the value from String to Int

 public string StrNumber{ get { if (Number == null) return ""; else return Number.ToString(); } set { try { Number = int.Parse(value); } catch{ Number = null; } } } 
+9
source

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> 
+10
source

Source: https://habr.com/ru/post/1265248/


All Articles