溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)

發(fā)布時間:2022-05-23 15:56:25 來源:億速云 閱讀:244 作者:iii 欄目:大數(shù)據(jù)

本篇內容主要講解“Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)”吧!

1.實現(xiàn)效果

Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)  
彈出登錄窗口,輸入驗證

2.業(yè)務場景

  1. 主窗口彈出登錄或者其他小窗口

  2. 表單驗證

3.編碼實現(xiàn)

3.1 添加Nuget庫

創(chuàng)建名為 “LoginSystem” 的Xamarin.Forms項目,添加2個Nuget庫

  1. Rg.Plugins.Popup 1.2.0.223:彈出框由該插件提供

  2. FluentValidation 8.6.1:表單驗證使用

3.2 工程結構

Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)

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進行實體規(guī)則驗證

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,F(xiàn)luentValidation的具體調用

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="沒有賬號?請聯(lián)系管理員。" 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

Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)

注冊彈出插件 

3.8 iOS項目中的AppDelegate.cs

Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)

到此,相信大家對“Xamarin.Forms登錄對話框及表單驗證怎么實現(xiàn)”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI