#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

Advertisements

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: