简体   繁体   English

在WPF中检测Drag'n'Drop文件?

[英]Detect Drag'n'Drop file in WPF?

Is it possible to have a WPF window/element detect the drag'n'dropping of a file from windows explorer in C# .Net 3.5? 是否可以让WPF窗口/元素从C#.Net 3.5中的Windows资源管理器中检测文件的拖放操作? I've found solutions for WinForms, but none for WPF. 我找到了WinForms的解决方案,但没有WPF的解决方案。

Try the following : 尝试以下方法:

    private void MessageTextBox_Drop(object sender, DragEventArgs e)
    {
        if (e.Data is DataObject && ((DataObject)e.Data).ContainsFileDropList())
        {
            foreach (string filePath in ((DataObject)e.Data).GetFileDropList())
            {
                // Processing here     
            }
        }
    }


    private void MessageTextBox_PreviewDragEnter(object sender, DragEventArgs e)
    {
        var dropPossible = e.Data != null && ((DataObject)e.Data).ContainsFileDropList();
        if (dropPossible)
        {
            e.Effects = DragDropEffects.Copy;
        }
    }

    private void MessageTextBox_PreviewDragOver(object sender, DragEventArgs e)
    {
        e.Handled = true;
    }

Unfortunately, TextBox, RichTextBox, and FlowDocument viewers always mark drag-and-drop events as handled, which prevents them from bubbling up to your handlers. 不幸的是,TextBox,RichTextBox和FlowDocument查看器始终将拖放事件标记为已处理,以防止它们冒泡到您的处理程序中。 You can restore drag-and-drop events being intercepted by these controls by force-handling the drag-and-drop events (use UIElement.AddHandler and set handledEventsToo to true) and setting e.Handled to false in your handler. 您可以通过强制处理拖放事件(使用UIElement.AddHandler并将handlerEventsToo设置为true),然后在处理程序中将e.Handled设置为false,来恢复这些控件截获的拖放事件。

Turns out I couldn't drop onto my TextBox for some reason, but dropping onto buttons works fine. 事实证明,由于某种原因我无法放到TextBox上,但是放到按钮上就可以了。 Got it working by adding 'AllowDrop="True"' to my window and adding drop event handler to button consisting of: 通过在我的窗口中添加“ AllowDrop =“ True”'并将添加事件处理程序添加到包含以下内容的按钮来使其正常工作:

private void btnFindType_Drop(object sender, DragEventArgs e)
{
  if (e.Data is System.Windows.DataObject &&
    ((System.Windows.DataObject)e.Data).ContainsFileDropList())
  {
    foreach (string filePath in ((System.Windows.DataObject)e.Data).GetFileDropList())
    {
      // Processing here
    }
  }            
}

I noticed that drag&drop in WPF is not as easy as it could be. 我注意到WPF中的拖放操作并非如此简单。 So I wrote a short article about this topic: http://www.wpftutorial.net/DragAndDrop.html 因此,我写了一篇有关该主题的简短文章: http : //www.wpftutorial.net/DragAndDrop.html

I had similar Issue, The drop events and drag enter events were not fired. 我有类似的问题,未触发drop事件和drag enter事件。 The issue was with the windows User Account Settings. 问题出在Windows用户帐户设置。 Set it to least secure setting and try the same code it works. 将其设置为最不安全的设置,然后尝试使用相同的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM