Xamarin.Forms登陸對話框及表單驗證

微信公衆號:Dotnet9,網站:Dotnet9問題或建議,請網站留言
若是您以爲Dotnet9對您有幫助,歡迎讚揚html

Xamarin.Forms登陸系統

內容目錄android

  1. 實現效果
  2. 業務場景
  3. 編碼實現
  4. 本文參考
  5. 源碼下載

1.實現效果

彈出登陸窗口,輸入驗證
彈出登陸窗口,輸入驗證ios

2.業務場景

  1. 主窗口彈出登陸或者其餘小窗口
  2. 表單驗證

3.編碼實現

3.1 添加Nuget庫

建立名爲 「LoginSystem」 的Xamarin.Forms項目,添加2個Nuget庫c#

  1. Rg.Plugins.Popup 1.2.0.223:彈出框由該插件提供
  2. FluentValidation 8.6.1:表單驗證使用

3.2 工程結構

LoginSystem工程結構

3.3 共享庫中的MainPage

彈出登陸窗口,MainPage.xaml中關鍵代碼微信

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

後臺彈出登陸窗口 MainPage.xaml.csapp

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進行實體規則驗證async

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接口mvvm

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

註冊彈出插件
Android項目中的MainActivity.cs註冊彈出插件

3.8 iOS項目中的AppDelegate.cs

註冊彈出插件
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 的微信公衆號,本站會及時推送最新技術文章

Dotnet9

相關文章
相關標籤/搜索