Tutorials Books Videos Forums

-- online Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Drag & Drop Files in WPF

by kirupa   | filed under Silverlight, WPF, and Blend

This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.

Dragging and dropping files is a fairly common task that you engage in frequently - whether you realize it or not. If you work with images a lot, you've probably dragged some images into an open instance of Adobe Photoshop and had those dragged files be automatically opened. Notepad is another great example. Dragging and dropping any files into Notepad will result in Notepad (often humorously) trying to make sense of the data - even if it the data isn't exactly text based.

There are many more examples, but regardless of your particular fond drag-and-drop recollection, someone somewhere had to customize their application to allow you to drop files into them. In this tutorial, I will show you how you can create one such application that does something when files are dropped into it.

More specifically, you will create an application that looks as follows:

When this application is running, you can drag some files and drop them onto the big green area. The names of the files you dropped will appear, and selecting and hovering over each file entry will display the tooltip of the file's location on disk.

Getting Started - Setting up the UI

What you are going to do is recreate what I described in the above example. It will be simple WPF application that contains a ListBox. As you drag and drop files into the ListBox, those files' names will be displayed inside it with an associated tooltip being set as well.

The first step in making all of this is having our basic UI created. Let's get started:

  1. Launch Expression Blend and create a new WPF Application. It doesn't really matter what name you give your application.

  2. After you have created your application, you will see a blank window. This window is a bit large for what we are going to do, so let's make it smaller. Select your Window and set its Width and Height to 350 and 250 respectively;

[ set your Window's dimensions via the Layout category ]

After changing the height, your window should look like the following:

[ notice that your window is now much smaller ]

  1. Now that your window is sized correctly, let's go ahead and add your Listbox control. From Blend's Asset Library, search for ListBox. Once you have found the ListBox, drag and drop the ListBox icon into your design surface to insert it:

[ you have just inserted a ListBox ]

That small square is actually your ListBox. I know it doesn't look like much right now, but rest assured that it is not a white square. If you are still skeptical, you can verify by looking in your object tree and seeing your Listbox appear:

[ notice that your ListBox now appears ]

  1. Let's make a few minor tweaks to our ListBox. First, let's give it a slightly different color so that it is more noticeable. Ensure your Listbox is selected, look in your Brushes category in the Properties pane, select the Background brush, and give it a light green-ish color:

[ give your ListBox a light green color ]

  1. Your listbox should now sport a light green background. The last thing we are going to do is make our listbox larger. With your Listbox control selected, on the design surface, drag the corner adorners to resize the ListBox to hit the edges of your Window:

[ your ListBox is now green! ]

  1. If you test your application right now by pressing F5, you will basically see something that looks as follows:

[ what your app looks like right now ]

Ok, so far, you have just created the UI, and your app does not do anything else. Very soon, and by very soon, I mean, starting in the next section, we will make your application useful.

In the previous section, you saw the introduction and created the basic UI that will power this application. In this page, let's go further and actually make your application work.

Allowing Files to be Dropped

By default, all WPF applications you create are not set up for files being dropped onto them. You have to explicitly enable this on a per element basis! What we are going to do next is allow files to be dropped into our ListBox control. Make sure your ListBox is selected, and from the Properties pane, search for the AllowDrop property:

[ find the AllowDrop property on your ListBox ]

Once you have found the AllowDrop property, turn it On by checking the checkbox next to it:

[ enable the AllowDrop property by checking it ]

If you are running a version of Expression Blend that is older than Version 3, despite the AllowDrop property being checked, there is a bug where what you see in the UI does not map to what is written in the XAML. Make sure that the XAML for your Listbox contains the AllowDrop=true value:

If you are curious to see what the results of setting the AllowDrop property are, run your application again by pressing F5. This time, while your application is running, drag some files from a folder and drop it onto your Listbox:

[ notice the cursor as I am trying to drop files into it ]

While my above screenshot doesn't show me actually dragging some files into the appllication, notice what my mouse cursor looks like though. My mouse cursor is indicating that what I am currently dragging over is a valid drop target. This is something that you couldn't really do before where you would have seen something like the following with the no-operation cursor displayed:

[ without drop enabled, your mouse cursor displays the no-op sign ]

We are about half-way done now. There is one more thing you need to do. Our ListBox currently has no name, and you will need a name for the coding portion later. So, let's just go ahead and give your ListBox the name DropListBox:

[ give your ListBox the name DropListBox ]

Ok, your application is now in a state where it is capable of receiving content that is dropped into it, and your ListBox now has a name. The next half of this involves actually listening for when a drop occurs and handling it appropriately, so let's move on.

Setting up the Events

Now that our application can have files dropped onto it, we need to assign some event handlers to deal with those events associated with the drop operation. Inside Blend, with your Listbox still selected, go to the Events list and find the Drop event:

Once you have found the Drop event, in the textbox right next to it, type in the name FilesDropped and press Enter. Once you have done this, you will suddenly find yourself either in Blend's code editor in Visual Studio's code editor seeing something that looks as follows:

private void FilesDropped(object sender, DragEventArgs e)
{
}

What you've just done is associated your ListBox's Drop event with the FilesDropped event handler. Whenever some file gets dropped over your listbox, this FilesDropped method will get called. Right now it doesn't do much, but we'll add the code that makes it do things in the next section.

In the previous section, you enabled drop support and hooked up the events needed to handle any files that get dropped into your ListBox. In this page, we will go further and add some code that will display the file name along with a tooltip for any files that get dropped.

Adding More Code

Right now, all you have is an empty event handler called FilesDropped. What you are going to do is copy and paste the following code into your FilesDropped event handler:

private void FilesDropped(object sender, DragEventArgs e)
{
  if (e.Data.GetDataPresent(DataFormats.FileDrop))
  {
  DropListBox.Items.Clear();
  string[] droppedFilePaths =
  e.Data.GetData(DataFormats.FileDrop, true) as string[];
  foreach (string droppedFilePath in droppedFilePaths)
  {
  ListBoxItem fileItem = new ListBoxItem();
  fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
  fileItem.ToolTip = droppedFilePath;
  DropListBox.Items.Add(fileItem);
  }
  }
}

Once you have done this, if you run your application and drop files into it, you will notice that they appear inside your ListBox. Hovering over each item in your ListBox displays a tooltip containing the item's full path - just like what I described in the example on the first page.

Let's now look at the code in greater detail:

if (e.Data.GetDataPresent(DataFormats.FileDrop))

The very first thing we do is check to make sure that the drop operation we are looking for is indeed a drop. I can do this easily by using just the built-in methods, and that is made possible by the e object - which is the DragEventArgs parameter that any event handler listening to the Drop event provides.

You may be wondering why I check explicitly for FileDrop. After all, am I not in the Drop event's event handler? The reason is that you cannot assume that what is being dropped is a file. For example, you could easily drag a paragraph of text from Microsoft Word and drop it into your window. In this case, you can't treat what has been dropped as a file. There are other little variations you have to deal with, and you can explore some of them by looking through all of the various things the DataFormats class provides besides FileDrop.

Once I verify that this drop event handler is dealing with dropped content that contains files, then I can continue!


DropListBox.Items.Clear();

The first thing I do is clear out all the files our ListBox is currently storing. This ensures that the ListBox only shows the files from the current drop operation. Pretty straightforward.


string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];

In this line, for every file that was included as part of the drop, I am getting an array of the file paths. Notice that the DataFormats.FileDrop code makes an appearance again. The reason is that, this time, I am filtering on only files that have been dropped by using the GetData method. Remember, in the previous check using GetDataPresent, I merely see if something in our collection of data is a file. This time, I explicitly filter out everything that isn’t a file and storing the data that remains in an array of strings.


foreach (string droppedFilePath in droppedFilePaths)
{
  ListBoxItem fileItem = new ListBoxItem();
  fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
  fileItem.ToolTip = droppedFilePath;
  DropListBox.Items.Add(fileItem);
}

In the next line, I am simply setting up my foreach statement to go through each filepath (droppedFilePath) from the array of filepaths (droppedFilePaths) my earlier filtering operation returns. Any code you see inside this block is executed each time for each file that is contained inside droppedFilePaths.


ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
DropListBox.Items.Add(fileItem);

The final thing to do once you have the filepath is to add it to our Listbox itself. To do this, I create a new ListBoxItem. This ListBoxItem does two things - It displays the name of the file, and when you hover over it, it displays the full path of the file as a tooltip.

You can display the name of the file from your full filepath by using the Path (System.IO, not System.Windows.Shapes) class’s GetFileNameWithoutExtension method. Setting the Tooltip is much easier. Simply set your Listbox’s Tooltip property to the filepath – which you already have from your droppedFilePath object.

The last thing to do once you have set your ListBoxItem’s Content and Tooltip properties is to add it to our Listbox itself. This ensures that you can actually see your ListBoxItem. That is handled by calling the Add method on DropListBox’s Items collection.


Conclusion

Hopefully this tutorial gave you a basic overview of how to write a simple application that supports dropping of files into it. One thing you need to keep in mind is that the range of content that one can drop into your application goes well beyond files. While what gets dropped will be different, the code that I've provided can easily be modified and extended to support other cases easily.

In case you are curious to know how my implementation of this looks like, feel free to download the source files below:

Extract the files and open the project in Blend or Visual Studio to take a deeper look at my version of what you have done in this tutorial.


Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--