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

时间:2015-03-31 08:45:32

标签: c# wpf listview drag-and-drop

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

现在我已经设置了listview,以便我可以拖放到它上面:

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

因此,这适用于拖放文件和处理它们。 但我不想检测文件丢弃的项目。

e.g。如果它被删除的IExplorerItemMyFolder对象,则将它们添加到该文件夹​​中。 这可能吗?

1 个答案:

答案 0 :(得分:0)

知道了,所以在RelayCommand我只需要深入了解DragEventArgs课程。

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