无法将文件从WPF列表视图拖到Windows资源管理器
本文关键字:视图 Windows 资源管理器 列表 WPF 文件 | 更新日期: 2023-09-27 18:13:55
我正试图拖动ListView
项并将其作为存储在该ListView
项中的位置的文件副本。当我开始拖动时,我成功地从ListView
项获取位置,但无法向操作系统发出信号,将该文件复制到指定位置。
private Point start;
ListView dragSource = null;
private void files_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.start = e.GetPosition(null);
ListView parent = (ListView)sender;
dragSource = parent;
object data = GetDataFromListBox(dragSource, e.GetPosition(parent));
Hide();
if (data != null)
{
string dataStr = ((UserData)data).Data.ToString();
string filepath = new System.IO.FileInfo(dataStr).FullName;
DataObject fileDrop = new DataObject(DataFormats.FileDrop, filepath);
DragDrop.DoDragDrop((ListView)sender, fileDrop, DragDropEffects.Copy);
}
}
private static object GetDataFromListBox(ListView source, Point point)
{
UIElement element = source.InputHitTest(point) as UIElement;
if (element != null)
{
object data = DependencyProperty.UnsetValue;
while (data == DependencyProperty.UnsetValue)
{
data = source.ItemContainerGenerator.ItemFromContainer(element);
if (data == DependencyProperty.UnsetValue)
{
element = VisualTreeHelper.GetParent(element) as UIElement;
}
if (element == source)
{
return null;
}
}
if (data != DependencyProperty.UnsetValue)
{
return data;
}
}
return null;
}
第二种方法GetDataFromListBox()
我发现在一个SO问题的答案。此方法从ListBox
或ListView
中提取正确的数据。
我是WPF的新手。请告诉我我错过了什么?
最后,我找到了一个解决方案:http://joyfulwpf.blogspot.in/2012/06/drag-and-drop-files-from-wpf-to-desktop.html
解决方案是使用SetFileDropList()
方法来分配文件拖放列表,而不是在DataObject
的构造函数中。以下是我修改后的工作代码:
ListView parent = (ListView)sender;
object data = parent.SelectedItems;
System.Collections.IList items = (System.Collections.IList)data;
var collection = items.Cast<UserData>();
if (data != null)
{
List<string> filePaths = new List<string>();
foreach (UserData ud in collection)
{
filePaths.Add(new System.IO.FileInfo(ud.Data.ToString()).FullName);
}
DataObject obj = new DataObject();
System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
sc.AddRange(filePaths.ToArray());
obj.SetFileDropList(sc);
DragDrop.DoDragDrop(parent, obj, DragDropEffects.Copy);
}