April 19, 2012

File Drag and Drop in WPF

Watch drag and drop to text boxes as they need special handling see Textbox Drag/Drop in WPF

Add to your control (or main window) declaration
AllowDrop="True" DragEnter="Window_DragEnter" Drop="Window_Drop"

In the code do something like this (this is a file drag/drop sample):
#region DragDrop

bool IsValidDropData(IDataObject draggedObj)
{
  bool res = false;
  IEnumerable<string> lst = draggedObj.GetData(DataFormats.FileDrop)
     as IEnumerable<string>;
  if (lst != null)
  { 
    // In this sample I am only taking the first file
 // the rest are ignored
    string first = lst.FirstOrDefault();
    if (!string.IsNullOrWhiteSpace(first))
    {
      FileInfo fi = new FileInfo(first);
      res = fi.Exists && HasValidFileExtension(fi);
    }
  }
  return res;
}

private bool HasValidFileExtension(FileInfo file)
{
  string[] validExtensions = new[] { ".xml" };

  bool res = false;
  res = (file != null) && validExtensions.Contains(file.Extension);
  return res;
}

private void Window_DragEnter(object sender, DragEventArgs e)
{
  if (IsValidDropData(e.Data))
  {
    e.Effects = DragDropEffects.Copy;
  }
  else
  {
    e.Effects = DragDropEffects.None;
  }
}

private void Window_Drop(object sender, DragEventArgs e)
{
  if (IsValidDropData(e.Data))
  {
    IEnumerable<string> files = e.Data.GetData(DataFormats.FileDrop)
        as IEnumerable<string>;
    string fileName = files.FirstOrDefault();
    if (!string.IsNullOrEmpty(fileName) && 
     File.Exists(fileName))
    {
       DoSomethingWith(fileName);
    }
  }
}

#endregion DragDrop

No comments: