You can just use Binding;
For example i want to hold a payment value that can not exceed 100. So i wrote a class
puclic class Payment : INotifyPropertyChanged
{
private int _amountDecimals;
public int AmountDecimals
{
get
{
return _amountDecimals;
}
set
{
if (value <= 100)
{
_amountDecimals = value;
}
OnPropertyChanged();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
So this property will set AmountDecimals value if user enters a value until it not exceeds 100
Then just set binding via code on Page constructor(or from xaml)
var myPayment =new Payment(); //this will hold page(view) data
BindingContext = myPayment;
var paymentEntry = new Entry();
paymentEntry.Keyboard = Keyboard.Numeric;
paymentEntry.SetBinding(Entry.TextProperty, "AmountDecimals");
So user enters a numeric value to the entry, but if he/she tries to enter a value more than 100, binding just reverse it to old value. You can just write your code to your class's properties like this (on setters). So if you want to some property to carry only 5 characters you can write something like this (codes can be wrong i did not compiled them :) )
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if ((value!= null && value.length <= 5) || value == null)
{
_name = value;
}
OnPropertyChanged();
}