C#WPF: Drag the file out this time!

C#WPF: Drag the file out this time!

Drag files from the WPF form

最后更新 12/3/2020 1:45 PM
沙漠尽头的狼
预计阅读 2 分钟
分类
WPF
标签
.NET C# WPF File drag and drop

回顾上篇文章:C# WPF:把文件给我拖进来!!!

拖拽文件进QuickApp中

This article completes the corresponding following: "C#WPF: Drag the file out this time!"

Check the effect in advance:

拖出文件

上面效果的代码很少,xaml 中只注册事件PreviewMouseLeftButtonDown即可:

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

The event handling code is as follows:

//处理文件拽出操作
private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // 目前每个菜单由一个Image和TextBlock组成,所以判断拖拽的是否是一个Image控件,其他目标控件的拖拽不处理
    var img = e.OriginalSource as Image;
    if (img == null || img.Tag == null)
    {
        return;
    }
    var menuInfo = img.Tag as MenuItemInfo;
    if(menuInfo==null)
    {
        return;
    }

    #region 拖拽代码

    ListView lv = new ListView();
    string dataFormat = DataFormats.FileDrop;
    DataObject dataObject = new DataObject(dataFormat, new string[] { menuInfo.FilePath});
    DragDropEffects dde = DragDrop.DoDragDrop(lv, dataObject, DragDropEffects.Copy);

    #endregion
}

关键的是后面的代码(拖拽代码源码仓库路径),需要将原文件路径通过DragDrop.DoDragDrop方法传入,操作系统帮我们处理了文件复制操作。

The above operation is still too simple. It is equivalent to just copying files at the operating system level. If you want to complete a drag-and-drop download function similar to Baidu's network disk (as shown below):

百度网盘拖拽下载文件

上面的功能,程序其实要做不少事情,需要监听拖放的路径,得到拖放路径后,就可以通过原文件网络路径进行下载了,建议阅读这篇文章,参考拖放下载文件操作:WPF 拖拽文件(拖入拖出),监控拖拽到哪个位置,类似百度网盘拖拽

另外,这篇文章对 WPF 的拖放写得也不做,建议阅读:WPF 之 DragDrop 拖放实例

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 1/26/2025

WPF internationalizes with custom XML files

This article describes in detail the methods of using custom XML files to achieve internationalization in WPF programs, including installing the necessary NuGet package, dynamically obtaining language lists, dynamically switching languages, using translation strings in code and xaml interfaces, etc. It also provides source code links to help developers easily internationalize WPF applications.

继续阅读