在WPF中将一个图像拖放到另一个图像上
本文关键字:图像 一个 拖放 另一个 WPF | 更新日期: 2023-09-27 18:17:37
我正试图将一个图像(此图像在树视图)移动到其他图像。使用以下处理程序
private void DragImage(object sender, MouseButtonEventArgs e)
{
Image image = e.Source as Image;
DataObject data = new DataObject(typeof(ImageSource), image.Source);
DragDrop.DoDragDrop(image, data, DragDropEffects.Copy);
}
private void DropImage(object sender, DragEventArgs e)
{
ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
Image imageControl = new Image() { Width = 50, Height = 30, Source = image };
Canvas.SetLeft(imageControl, e.GetPosition(this.Canvas).X);
Canvas.SetTop(imageControl, e.GetPosition(this.Canvas).Y);
this.Canvas.Children.Add(imageControl);
}
一旦我把图像放到画布上。它会粘在上面。我想再次把它移动到同一个画布上。你能建议一下如何实现吗?提前感谢
通过修改代码解决了这个问题。
private void DragImage(object sender, MouseButtonEventArgs e)
{
Image image = e.Source as Image;
DataObject data = new DataObject(typeof(ImageSource), image.Source);
DragDrop.DoDragDrop(image, data, DragDropEffects.All);
moving = true;
}
private void DropImage(object sender, DragEventArgs e)
{
Image imageControl = new Image();
if ((e.Data.GetData(typeof(ImageSource)) != null))
{
ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
imageControl = new Image() { Width = 50, Height = 30, Source = image };
}
else
{
if ((e.Data.GetData(typeof(Image)) != null))
{
Image image = e.Data.GetData(typeof(Image)) as Image;
imageControl = image;
if (this.Canvas.Children.Contains(image))
{
this.Canvas.Children.Remove(image);
}
}
}
Canvas.SetLeft(imageControl, e.GetPosition(this.Canvas).X);
Canvas.SetTop(imageControl, e.GetPosition(this.Canvas).Y);
imageControl.MouseLeftButtonDown += imageControl_MouseLeftButtonDown;
this.Canvas.Children.Add(imageControl);
}
void imageControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Image image = e.Source as Image;
DataObject data = new DataObject(typeof(Image), image);
DragDrop.DoDragDrop(image, data, DragDropEffects.All);
moving = true;
}