Exploring Drag and Drop in Xamarin Forms

In Xamarin Forms 5 the ability for doing drag and drop was released. In this article, I’ll explore it and show you how to use it by creating a simple Schedule UI, which will have the ability to drag event cards and drop them over a Trash icon to delete them.

How it works

To work with Drag/Drop, XF released two new GestureRecognizers that can be added to any UI element: DragGestureRecognizer and DropGestureRecognizer.

You just need to add the DragGestureRecognizer to the element you want to drag.

And a DropGestureRecognizer to the element where you want to drop it.

It also provides events/commands that can be used to detect when it starts dragging (DragStartingCommand, DragStarting) or dropping (DragOverCommand, DragLeaveCommand, DropCommand, DragOver).

Let’s use it

First, we are going to create a model that will represent our events:

Then create a ViewModel that will contain the list of events:

Create the view that will show the events and add the DragGestureRecognizer to a Frame inside the CollectionView DataTemplate, then a DropGestureRecognizer to the Trash Image.

In the ViewModel, we will use the DragStartingCommand and DragStartingCommandParameter to pass the event that was dragged to the ViewModel, and the DropCommand to detect when it was dropped over the trash icon to delete the event.

Result

That’s how easy it is to add drag/drop in our XF apps. If you want to continue learning about it, I recommend you to read Xamarin Forms Documentation or check this awesome video by Gerald Versluis.

You can find the full source code here.

Happy coding!

You may also like

1 Comment