Shake Boxes with MAUI and Xamarin.Forms
Let’s get shaking using Xamarin.Forms and .NET MAUI.
Shake using MVVM
LoginView.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="http://prismlibrary.com"
x:Class="Xeno.FungKuFit.Client.Views.AppLaunch.AccountLoginView"
prism:ViewModelLocator.AutowireViewModel="True">
<StackLayout>
<Label Text="Email" />
<Entry Text="{Binding UserEmail}"
TranslationX="{Binding ShakeUserX}" />
<Label Text="Password" />
<Entry Text="{Binding UserPass}"
TranslationX="{Binding ShakePasswordX}" />
<Button Text="Login" Command="{Binding CmdShakeBox}" />
</StackLayout>
</ContentPage>
LoginViewModel.cs
using System.Threading.Tasks;
using Prism.Commands;
namespace TestApp.ViewModels
{
public class ShakeViewModel
{
DelegateCommand CmdShakeBox => new DelegateCommand(async () =>
{
await ShakeBoxAsync();
}
/// <summary>Gets or sets the TranslateX value to shake the Password box by.</summary>
/// <value>X-axis translation offset.</value>
public int ShakePasswordX
{
get => _shakePasswordX;
set => SetProperty(ref _shakePasswordX, value);
}
private async Task ShakeBoxAsync()
{
int timeout = 50;
ShakePasswordX = -15;
await Task.Delay(timeout);
ShakePasswordX = 15;
await Task.Delay(timeout);
ShakePasswordX = -10;
await Task.Delay(timeout);
ShakePasswordX = 10;
await Task.Delay(timeout);
ShakePasswordX = -5;
await Task.Delay(timeout);
ShakePasswordX = 5;
await Task.Delay(timeout);
ShakePasswordX = 0;
}
}
}