如何将项目拖放到 ListView 中并检测它被放到的项目

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

所以我有一个 ListView,其中包含 MyFilesMyFolders 的列表 这两个 类 都实现了我的接口 IExplorerItem

现在我已经设置了我的列表视图,这样我就可以像这样拖放到它上面了:

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

命令是:

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

所以这对于拖放文件和处理文件来说效果很好。 但我不想检测文件被放置在哪个项目上。

例如如果 IExplorerItem 它被拖放到 MyFolder 对象上,则将它们添加到文件夹中。 这可能吗?

知道了,所以在我的 RelayCommand 中,我只需要更深入地研究 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
                    }
                }
            }
    }
}