Monday, July 12, 2010

Drag N Drop Of images in WPF

I have designed an application  to drag and drop one image onto other. Basically it requires
  • Mouse Down Event
  • Mouse Move Event
  • Drop Event
  • Allow Drop Property
Lets create a sample application
I take 2 pictures & 2empty images & place them on my canvas
Something like this




















The 2 Empty  images should implement  Drop Event.
Also their Allow Drop property should be true
Other two source images should implement Mouse Down & Mouse Move events.

Capture the mousedown event & keep flag

 private void Source_MouseDown(object sender, MouseButtonEventArgs e)
    {
            IsMouseDown = true;
     }

once mouse down event. copy the source image's path as dragdrop event something like this
private void Source_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseDown)
            {
                Image sourceImage = e.Source as Image;
                                             
                DataObject data = new DataObject(typeof(ImageSource), sourceImage.Source);
                DragDrop.DoDragDrop(sourceImage, data, DragDropEffects.Copy);
            }
            IsMouseDown = false;
        }



There are 6 operations that you can do as a part of  DODragDropEvent

  • DragDropEffects.Copy
  • DragDropEffects.All
  • DragDropEffects.Link
  • DragDropEffects.Move
  • DragDropEffects.None
  • DragDropEffects.Scroll

I am copying the Image's source in DataObject which will passed to DragEvents

Once you drop the mouse onto Destination image's area. Drop events gets fired. Here we need to extract the image's source & set the destination's Images source accordingly.
  private void Destination_Drop(object sender, DragEventArgs e)
        {
            ImageSource DestinationImageSource = e.Data.GetData(typeof(ImageSource)) as ImageSource;
            Image DestinationImage = e.Source as Image;
            DestinationImage.Source = DestinationImageSource;
                   
        }


That's it, Drag & drop is achieved.

2 comments:

  1. No it is not working Drop event is not firing eventhough is set allowdrop property t otrue

    ReplyDelete
  2. not working, can you share source codes?

    ReplyDelete