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.
Quick Links:
Project Setup:
- Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
- 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:
- In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
- In the Additional information window, click the Create button:
- 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
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:
Tweet
0 comments:
Please Comment about the Posts and Blog