Detect Drag'n'Drop file in WPF?

跟風遠走 提交于 2019-12-20 18:47:09

问题


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? I've found solutions for WinForms, but none for WPF.


回答1:


Unfortunately, TextBox, RichTextBox, and FlowDocument viewers always mark drag-and-drop events as handled, which prevents them from bubbling up to your handlers. 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.




回答2:


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;
    }



回答3:


Turns out I couldn't drop onto my TextBox for some reason, but dropping onto buttons works fine. Got it working by adding 'AllowDrop="True"' to my window and adding drop event handler to button consisting of:

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
    }
  }            
}



回答4:


I noticed that drag&drop in WPF is not as easy as it could be. So I wrote a short article about this topic: http://www.wpftutorial.net/DragAndDrop.html




回答5:


I had similar Issue, The drop events and drag enter events were not fired. The issue was with the windows User Account Settings. Set it to least secure setting and try the same code it works.



来源:https://stackoverflow.com/questions/332859/detect-dragndrop-file-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!