armandasalmd
armandasalmd

Reputation: 179

Image drag and drop (WPF Window)

I need to drag and drop from Image img2 to Image img1. That means that I want to copy img2 when I drag it on img1. Program is starting, but destination Image img1 is not changing after I drag Image img2 on it.

How to solve this problem to make it work ?

My code below:

XAML:

<Canvas Name="va">
        <Image Name="img1" Height="100" Width="100" AllowDrop="True" Drop="img1_Drop" />
        <Image Name="img2" Height="100" Width="100" Source="Resources/eye.bmp" 
               MouseLeftButtonDown="img2_MouseLeftButtonDown" AllowDrop="True" />
</Canvas>

C# code:

private void img2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Image image = e.Source as Image;
    DataObject data = new DataObject(typeof(ImageSource), image.Source);
    DragDrop.DoDragDrop(image, data, DragDropEffects.All);
}

private void img1_Drop(object sender, DragEventArgs e)
{
    Image imageControl = (Image)sender;
    if ((e.Data.GetData(typeof(ImageSource)) != null))
    {
        ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
        imageControl = new Image() { Width = 100, Height = 100, Source = image };
        img1 = imageControl;
    }
}

Upvotes: 2

Views: 8748

Answers (1)

Clemens
Clemens

Reputation: 128146

Assigning img1 = imageControl; will not add a new Image control to the Canvas.

You should instead simply assign the Source property of img1:

img1.Source = (ImageSource)e.Data.GetData(typeof(ImageSource));

Upvotes: 2

Related Questions