Detect Long Press in .NET MAUI App using TouchBehavior

 implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI Community Toolkit

Introduction

In this tutorial, we will show you how to implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI Community Toolkit. Learn how to trigger long press events or commands with parameters and see a live example of updating a button image on a successful long press.

Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
    Open visual studio
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
    Create New Project
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
    Configure your app
  • In the Additional information window, click the Create button:
    Addtional Information
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app
    Android Emulator Run

Install Plugin

We need to install the "CommunityToolkit.MAUI" by searching in nuget manager and click "Install" to install the plugin

Implementation

Here, we will add the long press behaviour to the image control and you can use as per your need:

  • Add the below code in the xaml file to have wire-up the event or command between the designer and view model. Add Namespace
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
  • Add the following code in your element. In this example, I used Image control
    <Image.Behaviors>
          <toolkit:TouchBehavior LongPressCommand="LongPressCommand" LongPressDuration="2000" />
    </Image.Behaviors>
  • The event code will be look like the below
    LongPressCommand = new Command(() =>
    {
    	count++;
    
    	if (count == 1)
    		CounterBtn.Text = $"Long pressed {count} time";
    	else
    		CounterBtn.Text = $"Long pressed {count} times";
    
    	SemanticScreenReader.Announce(CounterBtn.Text);
    });

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Demo:

Detect long press in dotnet MAUI app using touchbehaviour - Demo


Similar Articles