C# 在 WPF 中检测 Drag'n'Drop 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/332859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect Drag'n'Drop file in WPF?
提问by NoizWaves
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.
是否可以让 WPF 窗口/元素检测从 C# .Net 3.5 中的 Windows 资源管理器拖放文件?我找到了 WinForms 的解决方案,但没有找到 WPF 的解决方案。
采纳答案by Ed Ball
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.
不幸的是,TextBox、RichTextBox 和 FlowDocument 查看器总是将拖放事件标记为已处理,这可以防止它们冒泡到您的处理程序。您可以通过强制处理拖放事件(使用 UIElement.AddHandler 并将handledEventsToo 设置为true)并在处理程序中将e.Handled 设置为false 来恢复被这些控件拦截的拖放事件。
回答by NoizWaves
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:
事实证明,由于某种原因我无法放到我的 TextBox 上,但是放到按钮上效果很好。通过将 '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
}
}
}
回答by Ed Ball
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
我注意到 WPF 中的拖放并不像它想象的那么容易。所以我写了一篇关于这个话题的短文:http: //www.wpftutorial.net/DragAndDrop.html
回答by AvSomeren
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;
}
回答by DiAgo
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.
我有类似的问题,未触发放置事件和拖动输入事件。问题出在 Windows 用户帐户设置上。将其设置为最不安全的设置并尝试使用相同的代码。