如何在WPF中正确地允许Drag n Drop?

时间:2017-08-01 01:20:14

标签: c# wpf drag-and-drop

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

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

在Stack上测试一些解决方案

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

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

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

1 个答案:

答案 0 :(得分:0)

问题是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语句!如果没有这些,文本框处理程序将简单地覆盖您的工作。