To restrict the Entry
to only accept numbers you could use a Behavior or a Trigger.
Both of those will react to a user typing into them. So for your use, you could have the trigger or behavior look for any characters that are not numbers and remove them.
Something like this for a behavior (note that I wrote all this on SO and did not try compiling it, let me know if it does not work):
using System.Linq;
using Xamarin.Forms;
namespace MyApp {
public class NumericValidationBehavior : Behavior<Entry> {
protected override void OnAttachedTo(Entry entry) {
entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(entry);
}
protected override void OnDetachingFrom(Entry entry) {
entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(entry);
}
private static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if(!string.IsNullOrWhiteSpace(args.NewTextValue))
{
bool isValid = args.NewTextValue.ToCharArray().All(x=>char.IsDigit(x)); //Make sure all characters are numbers
((Entry)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
}
}
}
}
Then in your XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp;assembly=MyApp"> <!-- Add the local namespace so it can be used below, change MyApp to your actual namespace -->
<Entry x:Name="AgeEntry"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
Keyboard="Numeric">
<Entry.Behaviors>
<local:NumericValidationBehavior />
</Entry.Behaviors>
</Entry>
</ContentPage>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…