Entry binding to int? in Xamarin Forms
13,385
Solution 1
Entry accept a string. If you would like to bind a int property you should use a IValueConverter but I think the best solution is to use a String property than convert 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;
}
}
}
Solution 2
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>
Author by
Uros
I work in C# and Xamarin making APIs and small applications for Android and iOS.
Updated on June 04, 2022Comments
-
Uros about 2 years
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?
-
Jeroen Corteville over 5 yearsIs there a special reason that you are using the nullable int contstructor instead of doing result = intValue?
-
Arvis about 5 yearsYou can't convert to negative numbers, because conversation happens on every character input and minus sign get converted to null.