Shake Boxes with MAUI and Xamarin.Forms

Shake Boxes with MAUI and Xamarin.Forms

data codes through eyeglasses

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();
    }

    /// &lt;summary>Gets or sets the TranslateX value to shake the Password box by.&lt;/summary>
    /// &lt;value>X-axis translation offset.&lt;/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;
    }
  }
}