【问题标题】:How do I properly allow Drag n Drop in WPF?如何在 WPF 中正确允许拖放?
【发布时间】:2017-08-01 10:15:19
【问题描述】:

所以大约一年前,我在 WinForm 中开发这个应用程序,并决定在 WPF 中重新创建它以使其更多。我猜是最新的。 我刚刚遇到了我的第一个问题,允许拖放。 当我尝试拖放文件时,它不起作用,因为它给了我一个黑色圆圈,一条线穿过它。

这是我迄今为止尝试过的。 设置 AllowDrop = true。

在 Stack 上测试一些解决方案

测试了这个 http://codeinreview.com/136/enabling-drag-and-drop-over-a-grid-in-wpf/

但是我用谷歌搜索了多少我找不到答案,所以我问专业人士。 把它放在我身上我做错了什么,我将如何以正确的方式做到这一点? 这是我到目前为止的代码

<Grid AllowDrop="True" Drop="Grid_Drop" DragOver="Grid_DragOver">
    <TextBox Name="tbSomething" Text="stuff" Margin="181,140,183,152"></TextBox>
</Grid>

    private void Grid_Drop(object sender, DragEventArgs e)
    {
        if (null != e.Data && e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            var data = e.Data.GetData(DataFormats.FileDrop) as string[];
            // handle the files here!
        }
    }

    private void Grid_DragOver(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            e.Effects = DragDropEffects.Copy;
        }
        else
        {
            e.Effects = DragDropEffects.None;
        }
    }

【问题讨论】:

  • ...您是否尝试设置断点?

标签: c# wpf drag-and-drop


【解决方案1】:

问题在于 TextBox 有自己的拖放处理程序,不支持 FileDrop,这就是为什么你会得到 Drag.None 图标。

因此,您需要将处理程序放在 TextBox 处理程序的前面。像这样……

    <Grid>
        <TextBox Name="tbSomething" Text="stuff" Margin="20"  AllowDrop="True" PreviewDrop="Grid_Drop" PreviewDragOver="Grid_DragOver" ></TextBox>
    </Grid>

预览处理程序在文本框处理程序之前被调用。

然后在处理程序中...

    private void Grid_Drop(object sender, DragEventArgs e)
    {
        if (null != e.Data && e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            var data = e.Data.GetData(DataFormats.FileDrop) as string[];
            e.Handled = true;
            // handle the files here!
        }
    }

    private void Grid_DragOver(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }
        else
        {
            e.Effects = DragDropEffects.None;
        }
    }

注意 e.Handled = true 语句!如果没有这些,文本框处理程序将简单地覆盖您的工作。

【讨论】:

  • 我确信这在大多数情况下都行得通,但我仍然知道这个圈子。
  • 查看 XAML。我将处理程序从网格移动到文本框。它确实适用于您的情况。我用了你的代码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多