我必须创建一个用户必须输入其年龄的表单.我想用数字键盘:
<Entry
x:Name="AgeEntry"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
Keyboard="Numeric"
/>
Run Code Online (Sandbox Code Playgroud)
但它甚至显示小数点字符,我只想显示数字......
hva*_*an3 20
这两个都会对用户输入它们做出反应.因此,为了您的使用,您可以让触发器或行为查找任何非数字的字符并将其删除.
对于一个行为这样的事情(注意我在SO上写了所有这些并且没有尝试编译它,如果它不起作用,请告诉我):
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的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>
Run Code Online (Sandbox Code Playgroud)
小智 8
对我来说,简单的解决方案只是向 Entry 添加一个 TextChanged 句柄(这是 UI 特定代码,因此不会破坏 MVVM)
<Entry Text="{Binding BoundValue}" Keyboard="Numeric" TextChanged="OnTextChanged"/>
Run Code Online (Sandbox Code Playgroud)
然后在后面的代码中
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
//lets the Entry be empty
if ( string.IsNullOrEmpty(e.NewTextValue) ) return;
if ( !double.TryParse(e.NewTextValue, out double value) )
{
((Entry) sender).Text = e.OldTextValue;
}
}
Run Code Online (Sandbox Code Playgroud)
如果需要整数,请更改 int.Parse
| 归档时间: |
|
| 查看次数: |
19682 次 |
| 最近记录: |