#708 – Dragging a File Into a WPF Application
December 10, 2012 1 Comment
You can use drag-and-drop in WPF to allow a file to be dragged into your application, using the DataFormats.FileDrop format.
You first specify that you only support the FileDrop format.
private void Window_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Copy; else e.Effects = DragDropEffects.None; e.Handled = true; } private void Window_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effects = DragDropEffects.Copy; else e.Effects = DragDropEffects.None; e.Handled = true; }
When you call GetData in your Drop event handler, you get back a list of filenames being dropped. Below is an example where we set a Label to show the filename and then set the contents of a TextBlock to show the text from the file.
private void Window_Drop(object sender, DragEventArgs e) { string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop); lblFilename.Content = filenames[0]; txtContent.Text = File.ReadAllText(filenames[0]); }