Xamarin.Forms登录对话框及表单验证

微信公众号:Dotnet9,网站:Dotnet9问题或建议,请网站留言
如果您觉得Dotnet9对您有帮助,欢迎赞赏

Xamarin.Forms登录系统

内容目录

  1. 实现效果
  2. 业务场景
  3. 编码实现
  4. 本文参考
  5. 源码下载

1.实现效果

弹出登录窗口,输入验证

2.业务场景

  1. 主窗口弹出登录或者其他小窗口
  2. 表单验证

3.编码实现

3.1 添加Nuget库

创建名为 “LoginSystem” 的Xamarin.Forms项目,添加2个Nuget库

  1. Rg.Plugins.Popup 1.2.0.223:弹出框由该插件提供
  2. FluentValidation 8.6.1:表单验证使用

3.2 工程结构

3.3 共享库中的MainPage

弹出登录窗口,MainPage.xaml中关键代码

<StackLayout VerticalOptions="Center">    <Button Text="登录" BackgroundColor="#2196F3" Clicked="Login_Click"/></StackLayout>

后台弹出登录窗口 MainPage.xaml.cs

private async void Login_Click(object sender, EventArgs e){    await PopupNavigation.Instance.PushAsync(new LoginPage());}

3.4 Models中类文件

3.4.1 LoginUser.cs

namespace LoginSystem.Models{    class LoginUser    {        public string UserName { get; set; }        public string Password { get; set; }    }}

3.4.2 LoginUserValidator.cs

使用FluentValidation进行实体规则验证

using FluentValidation;namespace LoginSystem.Models{    class LoginUserValidator : AbstractValidator<LoginUser>    {        public LoginUserValidator()        {            RuleFor(x => x.UserName).NotEmpty().WithMessage("请输入账号")                .Length(5, 20).WithMessage("账号长度在5到20个字符之间");            RuleFor(x => x.Password).NotEmpty().WithMessage("请输入密码");        }    }}

3.4.3 NotifyPropertyChanged.cs

封装INotifyPropertyChanged接口

using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;namespace LoginSystem.Models{    public class NotifyPropertyChanged : INotifyPropertyChanged    {        protected bool SetProperty<T>(ref T backingStore, T value,            [CallerMemberName]string propertyName = "",            Action onChanged = null)        {            if (EqualityComparer<T>.Default.Equals(backingStore, value))                return false;            backingStore = value;            onChanged?.Invoke();            OnPropertyChanged(propertyName);            return true;        }        #region INotifyPropertyChanged        public event PropertyChangedEventHandler PropertyChanged;        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")        {            var changed = PropertyChanged;            if (changed == null)                return;            changed.Invoke(this, new PropertyChangedEventArgs(propertyName));        }        #endregion    }}

3.5 ViewModel中类文件

3.5.1 LoginViewModel.cs

登录视图的ViewModel,FluentValidation的具体调用

using FluentValidation;using LoginSystem.Models;using System;using System.Threading.Tasks;using System.Windows.Input;using Xamarin.Forms;namespace LoginSystem.ViewModel{    class LoginViewModel : NotifyPropertyChanged    {        public INavigation Navigation { get; set; }        public LoginUser LoginUserIns { get; set; }        string userName = string.Empty;        public string UserName        {            get { return userName; }            set { SetProperty(ref userName, value); }        }        string password = string.Empty;        public string Password        {            get { return password; }            set { SetProperty(ref password, value); }        }        private readonly IValidator _validator;        public LoginViewModel()        {            _validator = new LoginUserValidator();        }        private ICommand loginCommand;        public ICommand LoginCommand        {            get            {                return loginCommand ?? (loginCommand = new Command(ExecuteLoginCommand));            }        }        private string validateMsg;        public string ValidateMsg        {            get            {                return validateMsg;            }            set            {                SetProperty(ref validateMsg, value);            }        }        private async void ExecuteLoginCommand(object obj)        {            try            {                if (LoginUserIns == null)                {                    LoginUserIns = new LoginUser();                }                LoginUserIns.UserName = userName;                LoginUserIns.Password = password;                var validationResult = _validator.Validate(LoginUserIns);                if (validationResult.IsValid)                {                    //TODO 作服务端登录验证                    ValidateMsg = "登录成功!";                }                else                {                    if (validationResult.Errors.Count > 0)                    {                        ValidateMsg = validationResult.Errors[0].ErrorMessage;                    }                    else                    {                        ValidateMsg = "登录失败!";                    }                }            }            catch (Exception ex)            {                ValidateMsg = ex.Message;            }            finally            {            }            await Task.FromResult("");        }    }}

3.6 Views中的视图文件

3.6.1 LoginPage

登录窗口LoginPage.xaml,引入弹出插件Rg.Plugins.Popup,设置弹出框动画,绑定FluentValidation验证提示信息 “ValidateMsg”

<?xml version="1.0" encoding="utf-8" ?><pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"                 xmlns:d="http://xamarin.com/schemas/2014/forms/design"                 xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"                 xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"                 mc:Ignorable="d"             x:Class="LoginSystem.Views.LoginPage">    <pages:PopupPage.Resources>        <ResourceDictionary>            <Color x:Key="Primary">#2196F3</Color>        </ResourceDictionary>    </pages:PopupPage.Resources>    <pages:PopupPage.Animation>        <animations:ScaleAnimation DurationIn="400"                                   DurationOut="300"                                   EasingIn="SinOut"                                   EasingOut="SinIn"                                   HasBackgroundAnimation="True"                                   PositionIn="Center"                                   PositionOut="Center"                                   ScaleIn="1.2"                                   ScaleOut="0.8" />    </pages:PopupPage.Animation>    <Grid VerticalOptions="Center" Margin="40,20" HeightRequest="400">        <Frame CornerRadius="20" BackgroundColor="White">            <StackLayout Spacing="20" Padding="15">                <Image Source="person.png" HeightRequest="50" VerticalOptions="End"/>                <Entry x:Name="entryUserName" Text="{Binding UserName}" Placeholder="账号"                       PlaceholderColor="#bababa" FontSize="16"/>                <Entry IsPassword="True" Text="{Binding Password}" Placeholder="密码"                        PlaceholderColor="#bababa" FontSize="16"/>                <Button Margin="0,10,0,0" Text="登录" BackgroundColor="{StaticResource Primary}"                         TextColor="White" HeightRequest="50" VerticalOptions="Start"                        Command="{Binding LoginCommand}"/>                <Label Text="{Binding ValidateMsg}" TextColor="Red" HorizontalOptions="Center"/>                <Label Text="没有账号?请联系管理员。" HorizontalOptions="Center" FontSize="12"/>            </StackLayout>        </Frame>    </Grid></pages:PopupPage>

后台LoginPage.xaml.cs绑定ViewModel LoginViewModel,需要设置Navigation到LoginViewModel的属性Navigation,用于ViewModel中验证成功时返回主窗口使用

using LoginSystem.ViewModel;using Rg.Plugins.Popup.Pages;using Xamarin.Forms.Xaml;namespace LoginSystem.Views{    [XamlCompilation(XamlCompilationOptions.Compile)]    public partial class LoginPage : PopupPage    {        LoginViewModel ViewModel = null;        public LoginPage()        {            if (ViewModel == null)            {                ViewModel = new LoginViewModel();            }            this.BindingContext = ViewModel;            ViewModel.Navigation = Navigation;            InitializeComponent();        }    }}

3.7 Android项目中的MainActivity.cs

注册弹出插件

3.8 iOS项目中的AppDelegate.cs

注册弹出插件

4.本文参考

Houssem Dellai 大神的学习视频:Popup in Xamarin Forms

Fluent Validation With MVVM In Xamarin Forms Application

5.代码下载

文中代码已经全部提供

除非注明,文章均由 Dotnet9 整理发布,欢迎转载。

转载请注明本文地址:https://dotnet9.com/6841.html

欢迎扫描下方二维码关注 Dotnet9 的微信公众号,本站会及时推送最新技术文章

(0)

相关推荐

  • Xamarin.Forms弹出对话框插件

    微信公众号:Dotnet9,网站:Dotnet9,问题或建议,请网站留言: 如果您觉得Dotnet9对您有帮助,欢迎赞赏. Xamarin.Forms弹出对话框插件 内容目录 实现效果 业务场景 编码 ...

  • 如何在ASP.NET的Web API2专案中启用表单验证(Forms Authentication)

    WEB前端开发社区 昨天使用Visual Studio的2015年开发ASP.NET的Web API2专案时,有好几种专案范本可以选择,你可以从「空白」专案范本开始,也可以从「MVC」专案范本开始(记 ...

  • Thinkphp 表单验证规则

    'number'      => ':attribute必须是数字', 'integer'     => ':attribute必须是整数', 'float'       => ': ...

  • 【每周一坑】注册表单验证

    长假过后,大家都缓过神来了吗?在这里祝大家上班快乐~ 今天来个应用题.在使用各种网站和应用时,少不了要注册账号,这种注册表单大家应该屡见不鲜了吧. 一般这些表单都会做一些验证,如果你填写的信息不符合规 ...

  • 基于vuejs和element-ui的表单验证——循环表单和循环表格验证

    基于vuejs和element-ui的验证:循环表单验证.循环表格表单验证 代码: <!-- * @lastEditors: lingyang * @Date: 2019-12-16 15:31 ...

  • python测试开发django-26.表单提交之post登录案例

    前言 注册和登录功能实现都是post请求接口,只不过注册是往数据库插入数据,登录是从数据库里面查询数据. 本篇接着上一篇写个简单的登录页面请求,用户注册时密码加密存储,用户登录时候对输入的密码校验. ...

  • python测试开发django-100.Form表单类(forms.Form)

    前言 在 HTML 页面中利用 form 表单像后端提交数据,但是很多场景下我们都需要对用户的输入做校验,比如用户是否输入,输入长度以及格式问题. django 的 Form 表单类可以帮我们快速生成 ...

  • python测试开发django-102.验证时form表单error_messages

    前言 form表单验证前端输入内容是否合法时,可以定义error_messages参数,用于前端页面展示错误信息 error_messages参数 LoginForm 表单添加 常用的error_me ...

  • 施工/分包队伍如何管理?送上整套制度、流程表单!

    来源:豆丁施工 一.组织管理制度 1.分包单位现场负责人 必须常驻现场,履行组织管理职能.未经业主和总包方的批准不得随意更换,其间有事离开现场必须经总包方项目生产经理批准. 2.现场管理 必须设置专职 ...