您好,登錄后才能下訂單哦!
本篇內容主要講解“Xamarin.Forms登錄對話框及表單驗證怎么實現”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Xamarin.Forms登錄對話框及表單驗證怎么實現”吧!
主窗口彈出登錄或者其他小窗口
表單驗證
創建名為 “LoginSystem” 的Xamarin.Forms項目,添加2個Nuget庫
Rg.Plugins.Popup 1.2.0.223:彈出框由該插件提供
FluentValidation 8.6.1:表單驗證使用
彈出登錄窗口,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());
}
namespace LoginSystem.Models
{
class LoginUser
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
使用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("請輸入密碼");
}
}
}
封裝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
}
}
登錄視圖的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("");
}
}
}
登錄窗口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();
}
}
}
注冊彈出插件
到此,相信大家對“Xamarin.Forms登錄對話框及表單驗證怎么實現”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。