简体   繁体   中英

How do I properly allow Drag n Drop in WPF?

So I was working on this application in WinForm a year or so ago and decided to recreate it in WPF to make it more.. Up to date I guess. And I just ran into my first problem, allowing drag n drop. When I try to drag and drop a file it wont work because it gives me that black circle with a line going through it.

This is what I've tried so far. Setting AllowDrop = true.

Testing a few solutions on Stack

Tested this one http://codeinreview.com/136/enabling-drag-and-drop-over-a-grid-in-wpf/

But how much I Google I cant find an answer, so I'm asking the pros. Lay it on me what I am doing wrong and how would I do this in a proper way? This is the code I have so far

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

The problem is that TextBox has it's own drag and drop handlers which do not support FileDrop, which is why you get the Drag.None icon.

So you need to put your handler in front of the TextBox handler. Like this...

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

The preview handlers get called before the text box handlers.

Then in the handlers...

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

Note the e.Handled = true statements! Without these the textbox handlers will simply overwrite your work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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