图像拖放(WPF窗口)

时间:2016-03-20 10:27:56

标签: c# wpf xaml drag-and-drop

我需要从Image img2拖放到Image img1。这意味着我要在img2上拖动时复制img1。程序正在启动,但在我拖动Image img1后,目标Image img2未发生变化。

  

如何解决这个问题才能让它发挥作用?

我的代码如下:

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#代码:

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

1 个答案:

答案 0 :(得分:2)

分配img1 = imageControl;不会向画布添加新的图像控件。

您只需指定Source的{​​{1}}属性:

img1