JKennedy
JKennedy

Reputation: 18799

How to drag and drop item into ListView and detect item it was dropped onto

So I have a ListView which contains a list of MyFiles and MyFolders both of these classes implement my interface IExplorerItem

Now I have set up my listview so that I can drag and drop onto it like so:

<ListView ItemsSource="{Binding DisplayedItems}" AllowDrop="True">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Drop">
             <Command:EventToCommand Command="{Binding DropFiles}" PassEventArgsToCommand="True"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListView>

and the Command Is:

private RelayCommand<DragEventArgs> _dropFiles;

/// <summary>
/// Gets the DropFiles.
/// </summary>
public RelayCommand<DragEventArgs> DropFiles
{
    get
    {
        return _dropFiles
            ?? (_dropFiles = new RelayCommand<DragEventArgs>(
            args =>
            {
                if (args.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    // Note that you can have more than one file.
                    string[] files = (string[])args.Data.GetData(DataFormats.FileDrop);
                    //do my thing with my files
                }
            }
    }
}

So this works fine for dragging and dropping files and processing them. But I would not like to detect the item the file was dropped upon.

e.g. if the IExplorerItem it was dropped upon was a MyFolder object then add them to the folder. Is this possible?

Upvotes: 1

Views: 1062

Answers (1)

JKennedy
JKennedy

Reputation: 18799

Got it, so in my RelayCommand I just had to dig a little deeper into the DragEventArgs class.

private RelayCommand<DragEventArgs> _dropFiles;

/// <summary>
/// Gets the DropFiles.
/// </summary>
public RelayCommand<DragEventArgs> DropFiles
{
    get
    {
        return _dropFiles
            ?? (_dropFiles = new RelayCommand<DragEventArgs>(
            args =>
            {
                if (args.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    // Note that you can have more than one file.
                    string[] files = (string[])args.Data.GetData(DataFormats.FileDrop);
                    if ((args.OriginalSource as FrameworkElement).DataContext is MyFolder)
                    {
                      //put the files in a folder
                    }
                    else
                    {
                       //do something else
                    }
                }
            }
    }
}

Upvotes: 0

Related Questions