Drag & Drop in .Net Maui
Hi Devs, Today we will learn how to use Drag & Drop feature of .Net Maui.
In this example, we will have 2 shapes, a Square & Circle. We are going to aim at dropping the valid circle shape on an empty area.
How to enable Drag?
To enable the view to Drag from its position, We will use DragGestureRecognizer.
Make sure to set CanDrag=”True”
We can send custom data as the Drag starts by giving the DragStarting event.
e.Data.Properties is a DataPackagePropertySet of type IEnumerable having Key & Values properties.
In the above example, I have set the custom key as IsValidShape as true.
How to enable a Drop?
To enable the view to allow Drop, We will use DropGestureRecognizer. This is enabled on a view that serves as a Drop destination for other views which are set to CanDrag=”True”.
Make sure to set AllowDrop=”True”
We can get the custom property that we set during the DragStarting event in the Drop event.
There are many more events such as DragStarting, DropCompleted, Drop, DropLeave, and DragOver along with Commands of the same events to deal with the MVVM pattern. Check the full list of events & commands from here.
MainPage.xaml
The circleFrame & squareFrame both are enabled as a Drag with CircleDragStarted & SquareDragStarted respectively.
Whereas the third frame is set as Drop with ShapeDropped event.
MainPage.xaml.cs
Notice I have set custom data inside CircleDragStarted & SquareDragStarted with IsValidShape.
And fetched the same data in ShapeDropped event.
Thanks for the following blog till here, You can check my other blogs such as How to consume Rest API in .net Maui.
Happy Coding :D