我创建了两个用户输入字段,即用户名和密码。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:LoginUser"
x:Class="LoginUser.MainPage">
<StackLayout Spacing="20" Padding="50" VerticalOptions="Center">
<Entry x:Name="txtUsername" Placeholder="Username"></Entry>
<Entry x:Name="txtPassword" Placeholder="Password" IsPassword="True">
<Entry.Behaviors>
<local:ValidationBehavior/>
</Entry.Behaviors>
</Entry>
<Button Text="Log In" TextColor="White" BackgroundColor="##ff77D065" Clicked="Button_Onclick"></Button>
</StackLayout>
</ContentPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Text.RegularExpressions;
using UIKit;
namespace LoginUser
{
public class ValidationBehavior: Behavior<Entry>
{
const string pwRegex = @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$";
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
bool IsValid = false;
IsValid = (Regex.IsMatch(e.NewTextValue, pwRegex));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
}
如果从文本框中删除任何字符串字符(如lower,upper,special字符),我想显示显示警告。
答案 0 :(得分:0)
您可以通过静态Xamarin.Forms
的{{1}}属性从MainPage
项目的任何位置显示提醒,例如
App.Current
如果您想在await App.Current.MainPage.DisplayAlert("Test Title", "Test", "OK");
方法中调用提醒,则必须先添加HandleTextChanged
字词,如下所示:
async
我不知道显示提醒是否是一个好主意,也许它会显示async void HandleTextChanged(object sender, TextChangedEventArgs e)
{
IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
await App.Current.MainPage.DisplayAlert("Test Title", "Test", "OK");
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
Label
以下Entry
。
有关详细信息,请查看此example in github。
和this tutorial解释了如何使用行为绑定