拖放移动错误的面板

本文关键字:错误 移动 拖放 | 更新日期: 2023-09-27 18:02:13

我正在做一个包括几个面板的项目。我在表单的顶部有6个面板,在它们下面的2列中有6个面板。

我想从顶部面板内拖放图像到它下面的面板,反之亦然,在列之间。

然而,我目前的代码,我有一个问题,它有时(见下面的原因)移动错误的面板。

如果我将一个图像从一个面板拖到一个新的面板,并且我将鼠标悬停在一个已经包含图像的面板上,我最初拖动的图像将被我刚刚拖动的图像所取代。

事件代码:

    private void panel_MouseDown(object sender, MouseEventArgs e)
    {
        //we will pass the data that user wants to drag DoDragDrop method is used for holding data
        //DoDragDrop accepts two paramete first paramter is data(image,file,text etc) and second paramter 
        //specify either user wants to copy the data or move data
        source = (Panel)sender;
        DoDragDrop(source.BackgroundImage, DragDropEffects.Copy);
    }

    private void panel_DragEnter(object sender, DragEventArgs e)
    {
        //As we are interested in Image data only, we will check this as follows
        if (e.Data.GetDataPresent(typeof(Bitmap)))
        {
            e.Effect = DragDropEffects.Copy;
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }
    private void panel_DragLeave(object sender, System.EventArgs e)
    {
        sourcePanel = (Panel)sender;
    }
    private void panel_DragDrop(object sender, DragEventArgs e)
    {
        //target control will accept data here
        Panel destination = (Panel)sender;
        destination.BackgroundImage = (Bitmap)e.Data.GetData(typeof(Bitmap));
        sourcePanel.BackgroundImage = null;
    }

拖放移动错误的面板

我认为你想要sourcePanel在你的MouseDown事件,而不是source,因为你从来没有在你发布的代码再次引用source。当你将鼠标移进或移出一个面板时,DragLeave会触发,所以你不希望在那个时候设置你的源面板。

void panel_MouseDown(object sender, MouseEventArgs e) {
  sourcePanel = (Panel)sender;
  DoDragDrop(sourcePanel.BackgroundImage, DragDropEffects.Copy);
}

并忽略DragLeave事件:

void panel_DragLeave(object sender, EventArgs e) {
  //sourcePanel = (Panel)sender;
}