问题描述
我试图拖动的ListView
项目,并把它作为文件从存储在该位置的副本的ListView
项。我成功地让从我开始拖移的ListView
项目的位置,但无法信号操作系统,该文件复制到指定的位置。
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;
}
第二种方法 GetDataFromListBox()
我发现在做题的答案之一。此方法提取正确的数据从列表框
或的ListView
。
The second method GetDataFromListBox()
I found on one of the SO questions' answer. This method extracts the correct data from the ListBox
or ListView
.
我是新来的WPF。请告诉我,我缺少的是什么?
I am new to WPF. Please tell me what I am missing?
推荐答案
最后,我在这里找到了一个解决方案:的
Finally, I found a solution here: http://joyfulwpf.blogspot.in/2012/06/drag-and-drop-files-from-wpf-to-desktop.html
解决的办法是使用 SetFileDropList()
方法,而不是里面的数据对象
的构造函数指定文件下拉列表。以下是我的修改工作code:
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);
}
这篇关于无法从一个WPF的ListView拖动文件到Windows资源管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!