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 工程結構

LoginSystem工程結構

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

注冊彈出插件
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM