locked
How do you implement Drag N Drop in WPF? RRS feed

  • Question

  • My objective is to drag an image from windows explorer and drop it on a WPF form. Then the image control on the WPF form should display that image.

    I have been trying to look for WPF specific examples, but haven't had any luck.

    Any ideas?
    Thursday, January 7, 2010 1:30 PM

All replies

  •  

    This is a sample I have.  It may be a bit rough, but it should get you started.  Hope it helps.

     

    In you markup add these to your Window  AllowDrop="True" Drop="Window_Drop"

     

    /// <summary>

    /// EventHandler for Window.Drop event

    /// </summary>

    private void Window_Drop(object sender, DragEventArgs e)

    {

        DataObject dataObject = e.Data as DataObject;

     

        List<string> imageFiles = new List<string>();

     

        if (dataObject.ContainsFileDropList())

        {

            System.Collections.Specialized.StringCollection fileNames = dataObject.GetFileDropList();

            foreach (string fileName in fileNames)

            {

                if (IsImageFile(System.IO.Path.GetExtension(fileName)))

                {

                    imageFiles.Add(fileName);

                }

            }

        }

     

        LoadImages(imageFiles);

    }

     

    /// <summary>

    /// Create an Image and add it to your UI.

    /// 'canvas' was my root element in my Window.

    /// </summary>

    private void LoadImages(List<string> imageFiles)

    {

        foreach (string imageFile in imageFiles)

        {

            Image image = new Image();

            image.Height = 200;

            image.Width = 200;

            image.Stretch = Stretch.UniformToFill;

     

            BitmapImage bitmapImage = new BitmapImage();

            bitmapImage.BeginInit();

            bitmapImage.UriSource = new Uri(imageFile, UriKind.RelativeOrAbsolute);

            bitmapImage.EndInit();

     

            image.Source = bitmapImage;

            canvas.Children.Add(image);

        }

    }

     

    /// <summary>

    /// Just need to check whether or not your file

    /// is an image type that you are expecting

    /// </summary>

    private bool IsImageFile(string extension)

    {

        switch (extension)

        {

            case ".jpg":

            case ".png":

            case ".bmp":

            case ".tiff":

                return true;

            default:

                return false;

        }

    }

     


    Matt Hohn
    • Proposed as answer by Tj.. _ Sunday, February 7, 2010 8:18 PM
    Friday, January 8, 2010 9:16 AM
  • After 12 hours I've spent today, going through hundreds of examples, yours is only one that worked for me. Thanks a bunch for this!
    Monday, November 15, 2010 11:34 PM

  • The sample you shared is very valuable, It helps me a lot.
    Thursday, February 10, 2011 10:39 PM