如何使用HandleTextChanged事件显示显示警报消息?

时间:2017-09-07 15:45:54

标签: c# xamarin.forms

我创建了两个用户输入字段,即用户名和密码。

这是我的Xaml代码:

 <?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>

这是我的ValidationBehaviour.cs文件代码:

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字符),我想显示显示警告。

1 个答案:

答案 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解释了如何使用行为绑定