2015-09-22 47 views
1

我正在尝试将ListView项目拖放到该存储在该ListView项目中的文件副本中。我在开始拖动时成功从ListView项目获取位置,但无法向操作系统发出信号以将该文件复制到指定位置。无法将文件从WPF ListView拖动到Windows资源管理器

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()我在做题的回答的一个发现。此方法从ListBoxListView中提取正确的数据。

我是WPF的新手。请告诉我我错过了什么?

回答

0

最后,我发现了一个解决方案在这里:http://joyfulwpf.blogspot.in/2012/06/drag-and-drop-files-from-wpf-to-desktop.html

的解决方案是分配的,而不是内部DataObject的构造采用SetFileDropList()方法文件下拉列表。以下是我修改的工作代码:

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); 
} 
相关问题