WPF File Drag and Drop

WPF File Drag and Drop

When uploading files, usually an upload button is provided. Click to upload, a file (or directory selection dialog) pops up. After selecting a file (or directory), the file path is obtained from the dialog object, and then the upload operation is performed.

Last updated 11/27/2020 11:10 AM
沙漠尽头的狼
3 min read
Category
WPF
Tags
.NET WPF File Drag and Drop

1. Before Starting This Article

When uploading files, the typical approach is to provide an upload button, click to upload, pop up a file (or folder selection) dialog, select the file (or folder), obtain the file path from the dialog object, and then proceed with the upload operation.

Select file via dialog

Select file via dialog

The dialog selection code is as follows:

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Select Exe File";
openFileDialog.Filter = "Executable files|*.exe";
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "exe";
if (openFileDialog.ShowDialog() == false)
{
    return;
}
string txtFile = openFileDialog.FileName;

However, in general, the best user experience is to directly drag and drop files:

Baidu Netdisk drag-and-drop upload

Baidu Netdisk drag-and-drop upload

Below is a brief explanation of how to implement file drag-and-drop in WPF.

2. How to Drag and Drop Files in WPF?

It's actually very simple: just register two events on the drag-and-drop target control (or container): DragEnter and Drop.

Take a look at my implementation effect:

Drag file into QuickApp

Drag file into QuickApp

Register Events in XAML

Register events:

<Grid
  MouseMove="Grid_MouseMove"
  AllowDrop="True"
  Drop="Grid_Drop"
  DragEnter="Grid_DragEnter"
></Grid>

Event Handling Methods:

  1. Grid_DragEnter handling method
private void Grid_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effects = DragDropEffects.Link;
    }
    else
    {
        e.Effects = DragDropEffects.None;
    }
}

DragDropEffects.Link: Handle drag-and-drop file operation

  1. Grid_Drop handling method

This is the method that processes the actual drag-and-drop operation. After obtaining the dragged file path (if it's a shortcut file (with .lnk extension), you need to use a COM component (this is not the focus of this article; see the open-source project for details) to get the actual file path), you can then proceed with subsequent operations (e.g., file upload).

private void Grid_Drop(object sender, DragEventArgs e)
{
    try
    {
        var fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
        MenuItemInfo menuItem = new MenuItemInfo() { FilePath = fileName };

        // For shortcuts, we need to retrieve the target file path
        if (fileName.ToLower().EndsWith("lnk"))
        {
            WshShell shell = new WshShell();
            IWshShortcut wshShortcut = (IWshShortcut)shell.CreateShortcut(fileName);
            menuItem.FilePath = wshShortcut.TargetPath;
        }
        ImageSource imageSource = SystemIcon.GetImageSource(true, menuItem.FilePath);
        System.IO.FileInfo file = new System.IO.FileInfo(fileName);
        if (string.IsNullOrWhiteSpace(file.Extension))
        {
            menuItem.Name = file.Name;
        }
        else
        {
            menuItem.Name = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
        }
        menuItem.Type = MenuItemType.Exe;

        if (ConfigHelper.AddNewMenuItem(menuItem))
        {
            AddNewMenuItem(menuItem);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

3. End of This Article

The functionality is very simple; no need to delve too deep, just knowing how to use it is enough.

Keep Exploring

Related Reading

More Articles
Same category / Same tag 9/13/2025

Migration Series from WPF to Avalonia: Why I Must Migrate My WPF Application to Avalonia

In the past few years, our host computer software has mainly been developed using WPF and WinForm . These technologies work well on the Windows platform and have accompanied us from small-scale trial production to the current stage of large-scale delivery. However, with business development and changes in customer requirements, the single Windows technology stack has gradually become a hurdle we must overcome.

Continue Reading
Same category / Same tag 1/26/2025

Implementing Internationalization in WPF Using Custom XML Files

This article details the method of implementing internationalization in WPF applications using custom XML files, including installing the necessary NuGet packages, dynamically retrieving the language list, dynamically switching languages, using translated strings in code and XAML interfaces, and provides a source code link to help developers easily achieve internationalization in WPF applications.

Continue Reading