Add file to view

Drag & drop is a common feature in the Windows OS, mainly when you’re moving a file from one place to another. Did you know that you can drag files into your app though? Well it’s possible and it’s a great way to improve the user experience of your application when it is running on a desktop or tablet PC where you might want to upload or insert a file into a view.

The way this is done in your code is through a Boolean property and events on XAML controls which inherit from a UIElement. The Boolean property, AllowDrop, must be set to true on the control you want to enable dropping files onto. Also, the events for supporting drag & drop are DragEnter, DragLeave, DragOver and Drop. The two main events you’ll want to handle are DragOver so that you can turn on the support for drag & drop and Drop so you can get access to the collection of files that get dropped onto the control.

Your XAML will look something like this:

And the code behind will look something like this:

So now you know what to do, but how does the code work? We’ll start with the OnFileDragOver method.

When you drag a file over your control, you need to modify the DragEventArgs to let it know what kind of method you’re wanting from the drag & drop function, in this instance, we’re copying the file. You can also choose to Move the file which will copy it and then delete the original, or you can Link it.

You also have the choice here to modify the UI which shows when you drag a file over your control. In this instance, we modify the caption and show the content as we drag it over.

As well as handling the event, I’ve also added an element to the UI which overlays the control with a hint to the user that shows them they can add files to the view while they drag over. We show this element when we are dragging and hide it when we leave or drop the files. I’d recommend doing something similar in your own application as this is a great addition to the drag & drop user experience.

The OnFileDrop method is what handles your files that you drop onto the control. In this instance, we’re looking for StorageItems contained within the DataView property of the DragEventArgs and are specifically taking all of the StorageFiles and adding them to a GridView. It’s at this point that you can manipulate your files in anyway you wish, for example, filtering out the specific files you’re looking for by extension or opening the files into your app.

If you want to get a hold of the source I use for this, you can grab it on my GitHub here: github.com/jamesmcroft/DragDrop-UWP-Sample

Got any questions? Leave them below and I’ll get back in touch!

Keep coding!

Author James Croft

James is a .NET developer for Black Marble Ltd. with over 5 years app development experience in Microsoft platforms. He enjoys blogging, helping others learn to code, making YouTube videos, spending time with his girlfriend but most of all, penguins.

More posts by James Croft

Leave a comment