Drag-and-Drop Support in Xamarin.Forms: An Overview
Tags: xamarin, csharp, dotnet, mobile
Published: 2021-11-16 13:38:21

---
title: Drag-and-Drop Support in Xamarin.Forms: An Overview
published: true
date: 2021-11-16 11:00:05 UTC
tags: xamarin, csharp, dotnet, mobile
canonical_url: https://www.syncfusion.com/blogs/post/drag-and-drop-support-in-xamarin-forms-an-overview.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e716co55pcpm0a4sky8y.png
---
Nowadays, e-commerce businesses are making every effort to make the use of their stores as easy as possible for their customers. Part of that is a requirement to maintain multiple carts to check out items at different times. The drag-and-drop functionality of Xamarin.Forms comes in handy here. You can move items to a specific cart and proceed with purchases in batches.

This article shows you how to add drag-and drop-gesture support to your Xamarin.Forms applications to make your app more user-friendly.

## Drag and drop

Drag-and-drop support is a pointing device gesture. A user selects a virtual object in one location, then drags it to a different location or drops it onto another virtual object.

The drag-and-drop gestures in Xamarin.Forms enable users to select data, drag it from one onscreen location, and drop it to another onscreen location.

## Required packages

Install the following packages to enable the drag-and-drop support in Xamarin.Forms. You can enable this feature only in Xamarin.Forms version 5.0 and above.

![Required packages](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Required-packages.png)

## Drag source and drop target

The  **drag source** is the element responsible for the initiation of a drag-and-drop operation. It provides the data that we will transfer from one object to another by populating a data package object.

The  **drop target** is the element on which we will drop the drag source’s data.

## DragGestureRecognizer and its properties

In Xamarin.Forms, the **DragGestureRecognizer** class provides recognition for drag gestures.

The **DragGestureRecognizer** class defines the following properties.
<table style="height: 575px;" width="617">
<tbody>
<tr>
<td style="width: 310.909px;"><strong>Properties</strong></td>
<td style="width: 292px;"><strong>Definition</strong></td>
</tr>
<tr>
<td style="width: 310.909px;"><strong>CanDrag</strong></td>
<td style="width: 292px;">
<ul>
 	<li>It is of type <strong>bool</strong>.</li>
 	<li>It indicates whether the element can be a <strong>drag source</strong>.</li>
 	<li>The default value is <strong>true</strong>.</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 310.909px;"><strong>DragStartingCommand</strong></td>
<td style="width: 292px;">
<ul>
 	<li>It is of type <strong>ICommand</strong>.</li>
 	<li>It will be executed when the drag gesture is recognized.</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 310.909px;"><strong>DragStartingCommandParameter</strong></td>
<td style="width: 292px;">
<ul>
 	<li>It is of type <strong>object</strong>.</li>
 	<li>It is the <strong>parameter</strong> that is passed to the <strong>DragStartingCommand</strong>.</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 310.909px;"><strong>DropCompletedCommand</strong></td>
<td style="width: 292px;">
<ul>
 	<li>It is of type <strong>ICommand</strong>.</li>
 	<li>It will be executed when the drag source is dropped.</li>
</ul>
</td>
</tr>
<tr>
<td style="width: 310.909px;"><strong>DropCompletedCommandParameter</strong></td>
<td style="width: 292px;">
<ul>
 	<li>It is of type <strong>object</strong>.</li>
 	<li>It is the <strong>parameter</strong> that is passed to the <strong>DropCompletedCommand</strong>.</li>
</ul>
</td>
</tr>
</tbody>
</table>

Also, the **DragGestureRecognizer** class defines the **DragStarting** and **DropCompleted** events.

## DropGestureRecognizer and its properties

In Xamarin.Forms, the **DropGestureRecognizer** class provides recognition for drop gestures.

The **DropGestureRecognizer** class defines the following properties.

<table style="height: 696px;" width="595">
<tbody>
<tr style="height: 23px;">
<td style="height: 23px; width: 291.273px;"><strong>Properties</strong></td>
<td style="height: 23px; width: 289.818px;"><strong>Definition</strong></td>
</tr>
<tr style="height: 134px;">
<td style="height: 134px; width: 291.273px;">Allow Drop</td>
<td style="height: 134px; width: 289.818px;">
<ul>
 	<li> It is of type <strong>bool.</strong></li>
 	<li>It indicates whether the element can be a drop target.</li>
 	<li>The default value is <strong>true</strong>.</li>
</ul>
</td>
</tr>
<tr style="height: 119px;">
<td style="height: 119px; width: 291.273px;">DragOverCommand</td>
<td style="height: 119px; width: 289.818px;">
<ul>
 	<li>It is of type <strong>ICommand.</strong></li>
 	<li>It will be executed when the drag source is dragged over the drop target.</li>
</ul>
</td>
</tr>
<tr style="height: 119px;">
<td style="height: 119px; width: 291.273px;">DragOverCommandParameter</td>
<td style="height: 119px; width: 289.818px;">
<ul>
 	<li>It is of type <strong>object.</strong></li>
 	<li>It is the parameter that is passed to the <strong>DragOverCommand</strong>.</li>
</ul>
</td>
</tr>
<tr style="height: 159px;">
<td style="height: 159px; width: 291.273px;">DropCommand</td>
<td style="height: 159px; width: 289.818px;">
<ul>
 	<li>It is of type <strong>ICommand.</strong></li>
 	<li>It will be executed when the drag source is dropped over the drop target.</li>
</ul>
</td>
</tr>
<tr style="height: 119px;">
<td style="height: 119px; width: 291.273px;">DropCommandParameter</td>
<td style="height: 119px; width: 289.818px;">
<ul>
 	<li>It is of type <strong>object. </strong></li>
 	<li>It is the parameter passed to the <strong>DropCommand</strong>.</li>
</ul>
</td>
</tr>
</tbody>
</table>

Also, the **DropGestureRecognizer** class defines the **DragOver, DragLeave,** and **Drop** events.

## Displaying items using Syncfusion Xamarin.Forms ListView

The Syncfusion [Xamarin.Forms ListView](https://www.syncfusion.com/xamarin-ui-controls/xamarin-listview "Link to the Xamarin ListView control") control is a list interface. It can render a set of data items vertically or horizontally with a linear or grid structure.

We are going to use the ListView control to display a list of gift items and enable drag-and-drop gestures to move the gift items to the cart.

Refer to the following code example. Here, we will display the items vertically.

```html
<listView:SfListView
   x:Name="ItemsListView"
   Margin="10"
   ItemSpacing="10"
   AutoFitMode="DynamicHeight"
   SelectionBackgroundColor="Transparent"
   ItemsSource="{Binding ItemsCollection}">
   <listView:SfListView.LayoutManager>
        <listView:GridLayout SpanCount="2"/>
   </listView:SfListView.LayoutManager>
   <listView:SfListView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Frame BorderColor="Gray" CornerRadius="6">
                    <StackLayout>
                       <Image
                          Source="{Binding Image}"
                          HeightRequest="100"
                          WidthRequest="100"/>
                       <Label 
                          Text="{Binding Name}"
                          FontAttributes="Bold"
                          FontSize="16"
                          TextColor="Black">
                       </Label>
                       <Label 
                          Text="{Binding Price}"
                          FontSize="16"
                          TextColor="Black">
                       </Label>
                     </StackLayout>
                 </Frame>
              </StackLayout>
         </DataTemplate>
   </listView:SfListView.ItemTemplate>
</listView:SfListView>
```

![Displaying Items Using Syncfusion Xamarin.Forms ListView](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Displaying-Items-Using-Syncfusion-Xamarin.Forms-ListView.png)
_Displaying Items Using Syncfusion Xamarin.Forms ListView_

## How to enable drag and drop in Xamarin.Forms apps

Enable drag-and-drop support in your Xamarin.Forms application:

### Step 1: Enable dragging.

You can enable the drag gesture on an element by adding a **DragGestureRecognizer** object to its **GestureRecognizer** collection. Then, set the **CanDrag** property in the **DragGestureRecognizer** object to true.

The following XAML code demonstrates how to enable the drag gesture for image controls.

```html
<Image
   Source="user.png"
   HeightRequest="30"
   WidthRequest="30">
   <Image.GestureRecognizers>
       <DragGestureRecognizer CanDrag="True"/>
   </Image.GestureRecognizers>
</Image>
```

If you want to drag one or more controls inside the layout, then add a **DragGestureRecognizer** object to that layout’s **GestureRecognizer** collection.

The following XAML code demonstrates how to enable the drag gesture for the StackLayout, to use it inside the ListView ItemTemplate.

```html
<StackLayout>
  <Frame BorderColor="Gray" CornerRadius="6">
    <StackLayout>
      <Image
        Source="{Binding Image1}"
        HeightRequest="100"
        WidthRequest="100"/>
      <Label
        Text="{Binding Name}"
        FontAttributes="Bold"
        FontSize="16"
        TextColor="Black">
      </Label>
      <Label
        Text="{Binding Price}"
        FontSize="16"
        TextColor="Black">
      </Label>
      <StackLayout.GestureRecognizers>
        <DragGestureRecognizer
          CanDrag="True"/>
      </StackLayout.GestureRecognizers>
    </StackLayout>
  </Frame>
</StackLayout>
```

### Step 2: Building a data package.

Xamarin.Forms automatically builds a data package when we initiate a drag for the text and image controls. For other controls, we have to build our data package for the drag source.

The **DataPackage** class will represent the data packages with the following properties.

<table>
<tbody>
<tr>
<td width="312"><strong>Properties </strong></td>
<td width="312"><strong>Definition</strong></td>
</tr>
<tr>
<td width="312"><strong>Properties</strong></td>
<td width="312">
<ul>
 	<li>It is of type <strong>DataPackagePropertySet</strong> class.</li>
 	<li>It is a collection of properties with data in the <strong>DataPackage</strong>.</li>
</ul>
</td>
</tr>
<tr>
<td width="312"><strong>Image</strong></td>
<td width="312">
<ul>
 	<li>It is of type <strong>ImageSource</strong>.</li>
 	<li>It is the image element in the <strong>DataPackage</strong>.</li>
</ul>
</td>
</tr>
<tr>
<td width="312"><strong>Text</strong></td>
<td width="312">
<ul>
 	<li>It is of type <strong>string</strong>.</li>
 	<li>It is the text element in the DataPackage.</li>
</ul>
</td>
</tr>
<tr>
<td width="312"><strong>View</strong></td>
<td width="312">
<ul>
 	<li>It is of type <strong>DataPackageView.</strong></li>
</ul>
</td>
</tr>
</tbody>
</table>

In the DataPackagePropertySet class, the properties are stored as **Dictionary<string,object>****.**

#### Storing drag source data

Store any data (including images and text) associated with a drag source in the **DataPackage.Properties** collection. We can accomplish this in the handler for the **DragStarting** event.

The **DragStarting** event is triggered when a drag gesture is detected on the ListView items.

The following code demonstrates how the StackLayout in the ListView items’ DragGestureRecognizer registers the handler for the DragStarting event and executes the DragStarting handler.

```html
<StackLayout.GestureRecognizers>
  <DragGestureRecognizer
    CanDrag="True"
    DragStarting="OnDragStarting"/>
</StackLayout.GestureRecognizers>
```

You can modify the Properties collection in the DataPackage to store the StackLayout object.

```csharp
/// <summary>
/// Invoked when drag is started.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnDragStarting(object sender, DragStartingEventArgs e)
{
    var layout = (sender as Element).Parent as StackLayout;
    e.Data.Properties.Add("Layout", layout);
}
```

### Step 3: Enable drop.

You can enable the drop gesture on an element by adding a **DropGestureRecognizer** object to its GestureRecognizer collection. Then, set the **AllowDrop** property in the DropGestureRecognizer object to true.

We are going to use another ListView control to enable the drop gesture with a different layout.

The following code demonstrates the user’s collection ListView, where we will enable the drop gesture for the grid layout inside the ListView ItemTemplate.

```html
<listView:SfListView
  x:Name="UsersListView"
  IsVisible="False"
  AutoFitMode="DynamicHeight"
  SelectionBackgroundColor="Transparent"
  Orientation="Horizontal"
  HeightRequest="460"
  ItemSpacing="10"
  ItemsSource="{Binding UsersCollection}">
  <listView:SfListView.ItemTemplate>
    <DataTemplate>
      <Frame CornerRadius="6" BorderColor="Gray" Padding="10">
        <Grid>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
          </Grid.RowDefinitions>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
          </Grid.ColumnDefinitions>
          <StackLayout
            HorizontalOptions="CenterAndExpand"
            Grid.Row="0"
            Grid.ColumnSpan="2"
            Margin="10,0,10,0">
            <Image
              Source="users1.jpg"
              HeightRequest="70"
              WidthRequest="70"/>
            <Label
              HorizontalOptions="CenterAndExpand"
              Text="{Binding Name}"
              FontSize="20"
              FontAttributes="Bold"
              TextColor="Black"/>
          </StackLayout>
          <Label
            Grid.Row="1"
            Grid.Column="0"
            FontAttributes="Bold"
            IsVisible="False"
            FontSize="16"
            TextColor="Black"/>
          <Label
            Grid.Row="2"
            IsVisible="False"
            FontSize="16"
            Grid.Column="0"
            TextColor="Black"/>
          <Image
            Grid.Column="1"
            Grid.Row="1"
            Grid.RowSpan="2"
            HeightRequest="60"
            WidthRequest="60"/>
        </Grid>
      </Frame>
    </DataTemplate>
  </listView:SfListView.ItemTemplate>
</listView:SfListView>
```

The following screenshot shows the user’s collection using the ListView horizontally.

![Displaying Items Using Syncfusion Xamarin.Forms ListView](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Displaying-Items-Using-Syncfusion-Xamarin.Forms-ListView-1.png)
<figcaption>Displaying Items Using Syncfusion Xamarin.Forms ListView</figcaption>

Now, enable the drop gesture in the grid layout. Refer to the following code example.

```html
<Grid.GestureRecognizers>
    <DropGestureRecognizer
        AllowDrop="True"/>
</Grid.GestureRecognizers>
```

### Step 4: Processing a data package.

In Xamarin.Forms, a data package is processed when the drop event is triggered. The drop event is triggered when the drag source is dropped on the drop target.

Xamarin.Forms will automatically retrieve the data for text and image controls. For other controls, we have to retrieve the data from the data package in the handler of the Drop event, using the Properties collection of the DataPackage.

The following code demonstrates how to retrieve data from the data package for a StackLayout and use those values to show the dragged items in a user collection ListView.

```csharp
/// <summary>
/// Invoked when drag source is dropped over the drop target.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnDrop(object sender, DropEventArgs e)
{
   var itemsLayout = (StackLayout)e.Data.Properties["Layout"];
   //code to show the items in user collection.
}
```
![Dragging Items to add it in User's Cart](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Dragging-Items-to-add-it-in-Users-Cart.png)

![Dragging and Dropping Items to User's Cart](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Dragging-and-Dropping-Items-to-Users-Cart.png)
<figcaption>Dragging and Dropping Items to User’s Cart</figcaption>

## GitHub reference

For more details, refer to the complete example for [drag-and-drop support in Xamarin.Forms](https://github.com/SyncfusionExamples/drag-and-drop-support-in-xamarin "Link to the demo for drag-and-drop support in Xamarin.Forms").

## Conclusion

Thanks for reading! In this blog, we have learned how to use drag-and-drop gestures in Xamarin.Forms applications. With this, users can easily select items by just dragging and dropping them into the specific cart and proceed with purchases in batches.

Syncfusion’s [Xamarin](https://www.syncfusion.com/xamarin-ui-controls "Link to the Syncfusion Xamarin.Forms UI controls") suite offers over 150 UI controls, from basic editors to powerful, advanced controls like [DataGrid](https://www.syncfusion.com/xamarin-ui-controls/xamarin-datagrid "Link to Xamarin.Forms DataGrid"), [Charts](https://www.syncfusion.com/xamarin-ui-controls/xamarin-charts "Link to Xamarin.Forms Charts"), [ListView](https://www.syncfusion.com/xamarin-ui-controls/xamarin-listview "Link to the Xamarin.Forms ListView"), and [Rich Text Editor](https://www.syncfusion.com/xamarin-ui-controls/xamarin-rich-text-editor "Link to the Xamarin.Forms Rich Text Editor"). Try them out and leave your feedback in the comments section below!

You can also contact us through our [support forums](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/xamarin-forms "Link to Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Replicating a Social Profile UI in Xamarin.Forms](https://dev.to/karthickramasamy08/replicating-a-social-profile-ui-in-xamarin-forms-3edf-temp-slug-2742389 "Link to Replicating a Social Profile UI in Xamarin.Forms blog")
- [How to Reuse Xamarin.Forms Custom Renderers in .NET MAUI](https://dev.to/karthickramasamy08/how-to-reuse-xamarin-forms-custom-renderers-in-net-maui-18c8-temp-slug-8337623 "Link to How to Reuse Xamarin.Forms Custom Renderers in .NET MAUI blog")
- [Create a Wizard View in Xamarin.Forms: A Novice’s Guide](https://dev.to/karthickramasamy08/create-a-wizard-view-in-xamarin-forms-a-novice-s-guide-4286-temp-slug-9690565 "Link to Create a Wizard View in Xamarin.Forms: A Novice’s Guide blog")
- [Easily Create a Meeting Room Calendar Using Xamarin.Forms Scheduler](https://dev.to/karthickramasamy08/easily-create-a-meeting-room-calendar-using-xamarin-forms-scheduler-58c3-temp-slug-6689711 "Link to Easily Create a Meeting Room Calendar Using Xamarin.Forms Scheduler blog")