限制 Xamarin.Forms 中输入字段的输入长度和字符 [英] Restricting input length and characters for Entry field in Xamarin.Forms
问题描述
如何限制在 Xamarin.Forms 的 Entry 控件中输入的长度和字符.我需要创建自定义控件吗?有没有一种方法可以从 Entry(或其他控件)中派生出来,以便我可以应用必要的每个平台输入限制.
How can I restrict the length and characters entered in an Entry control in Xamarin.Forms. Do I need to create a custom control? Is there a way I can derive from Entry (or another control) so I can apply the necessary per-platform input limitations.
一个例子是一个数字字段,限制为最多 3 个字符,仅限数字.
An example would be a numeric field that is restricted to a maximum of 3 characters, digits only.
将 Entry 控件的 Keyboard 属性设置为 Keyboard.Numeric 仅为 iOS 设置键盘.它不限制实际的文本输入 - 即我仍然可以输入非数字字符.我也没有看到限制条目长度的方法.
Setting the Keyboard property of an Entry control to Keyboard.Numeric only sets the keyboard for iOS. It does not restrict the actual text entry - i.e. I can still enter non-digit characters. Nor do I see a way to limit the length of entry.
推荐答案
您可以限制输入字段中的字符数,如下所示,
You can restrict the number of charecters in the Entry field as given below,
int restrictCount = <your restriction length> //Enter your number of character restriction
Entry entry = new Entry();
entry.TextChanged += OnTextChanged;
void OnTextChanged(object sender, EventArgs e)
{
Entry entry = sender as Entry;
String val = entry.Text; //Get Current Text
if(val.Length > restrictCount)//If it is more than your character restriction
{
val = val.Remove(val.Length - 1);// Remove Last character
entry.Text = val; //Set the Old value
}
}
这篇关于限制 Xamarin.Forms 中输入字段的输入长度和字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!