How to Implement Drag and Drop in Windows Universal Apps ?

How to Implement Drag and Drop in Windows Universal Apps ?

Using Drag and Drop is a common requirement for  app developers. Drag and drop has been added to the list view in Windows 8.1, but it was limited to the List View control where the items inside the List View can be dragged, dropped and re ordered. But it was not available for any external UIElement. In windows 10, the feature has been more enhanced such that the drag and drop feature is supported by all UIElement and also even from the desktop file explorer the content can be dragged and dropped in the Windows Universal Apps. In the post let’s see how to add drag and drop feature in Windows Universal Apps using a sample application where the image from file explorer is dragged and dropped in the windows universal apps.

Let’s see how it works.

Setting the AllowDrop=”True” to the UIElement will enable the element to accept the content, when the user drag and bringing the content in to the UIElement’s area.

Subscribe for the event Drop and DragEnter for the UIElement for which the drag drop feature is added. Set the e.AcceptedOperation = DataPackageOperation.Copy; on the DragEnter event. So when the image is dragged inside the control then the control displays a visual representation to the user so the user can understand that the UIElement can accept the target.

private void Grid_DragEnter(object sender, Windows.UI.Xaml.DragEventArgs e)
{
    e.AcceptedOperation = DataPackageOperation.Copy;
}

Screenshot (1)

 Related Read : Drag and Drop XAML Controls from Toolbox to Document Outline

Once the image is dropped in to the UIElement, then the image has to be shown inside the UIElement. The data copied in the clipboard has to be read and add the content to the UIElement. This can be achieved by adding the following code in the Drop event of the UIElement.

private async void Grid_Drop(object sender, Windows.UI.Xaml.DragEventArgs e)
{
    var win =(StorageFile) (await e.DataView.GetStorageItemsAsync())[0];
    var image = new BitmapImage();
    image.SetSource(await win.OpenReadAsync());
    var ImageControl = new Image();
    ImageControl.Source = image;
    grid.Children.Add(ImageControl);
}

Screenshot (3)

Thus the image is copied from the file explorer to the Windows Universal App.

Hope this post might have helped in adding Drag and Drop feature for your Universal Apps.

Arun Kumar

Arun kumar Surya Prakash, is a  Developer  Consultant. He  is a Microsoft Certified Solution  Developer  for Store App Development, and a Azure Solution Developer. His core skills is on developing Windows Store App and Cross Platform App development. You can follow him @arunnov04