天天看點

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 的微信公衆号,本站會及時推送最新技術文章

時間如流水,隻能流去不流回。