Is it possible specify Xamarin Forms Entry Numeric Keyboard without comma or decimal point separator?

后端 未结 4 821
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 20:54

I have to create a form in which the user must input his age. I would like to use a numeric keyboard:

    

        
4条回答
  •  难免孤独
    2021-01-03 21:41

    if (!string.IsNullOrWhiteSpace(args.NewTextValue))
    {
        bool isValid = args.NewTextValue.ToCharArray().All(char.IsDigit);
    
        ((Editor)sender).Text = isValid ? args.NewTextValue : args.OldTextValue;
    }
    

    This prevents adding any non digit char into the Editor no matter where you added it. So if your cursor was in the middle of your number and you got for example 21h3 in @hvaughan3's answer you would just remove the last char giving you 21h with the non digit still being present.

    My answer will just use the value you had before adding the non digit char (213).

    But keep in mind! If you put this in a behavior and react to editor.TextChanged Event, this is still gonna change the Text for a brief second to the invalid value since this event triggers when it ALREADY was set. this is no OnTextChanging event. Same for @hvaughan3's answer. To prevent any issues you might get because of this, for example because you're also listening to OnTextChanged in Code behind, just add this line before working with the new text value

    if (!editor.Text.All(char.IsDigit)) return;
    

提交回复
热议问题