#708 – Dragging a File Into a WPF Application

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]);
        }

708-001

 

708-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #708 – Dragging a File Into a WPF Application

  1. Pingback: Dew Drop – December 10, 2012 (#1,459) | Alvin Ashcraft's Morning Dew

Leave a comment