问题
I am trying to drag a ListView item and drop it as a copy of file from the location stored in that ListView item. I am successfully getting the location from the ListView item when I start dragging but unable to signal Operating System to copy that file to the specified location.
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;
}
The second method GetDataFromListBox() I found on one of the SO questions' answer. This method extracts the correct data from the ListBox or ListView.
I am new to WPF. Please tell me what I am missing?
回答1:
Finally, I found a solution here: http://joyfulwpf.blogspot.in/2012/06/drag-and-drop-files-from-wpf-to-desktop.html
The solution was to assign file drop list using SetFileDropList() method, instead of inside DataObject's constructor. Following is my modified working code:
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);
}
来源:https://stackoverflow.com/questions/32725514/unable-to-drag-file-to-windows-explorer-from-a-wpf-listview