C# 拖放;落下移动错误的面板

C# 拖放;落下移动错误的面板,c#,C#,我正在做一个包含几个面板的项目。我在表格顶部有6个面板,在下面的2列中有6个面板 我想将图像从顶部面板拖放到它下面的面板,反之亦然,并在列之间拖放 然而,对于我当前的代码,我有一个问题,它有时(参见下面的原因)会移动错误的面板 如果我将图像从一个面板拖动到一个新面板,并将鼠标悬停在已包含图像的面板上,则最初拖动的图像将替换为刚才拖动的图像 事件代码: private void panel_MouseDown(object sender, MouseEventArgs e) {

我正在做一个包含几个面板的项目。我在表格顶部有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
,而不是
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;
}

任何关于“有时”的澄清@Kilazur和“有时”我的意思是:“如果我将一个图像从一个面板拖动到一个新面板上,并且我将鼠标悬停在一个已经包含图像的面板上,我最初拖动的图像将被我刚才拖动过的图像替换。”最初拖动的图像就是面板中包含的图像,对吗?对我来说太“拖累”了;)从我对这个问题的理解来看,你可能不需要一个拖拽处理程序。@Kilazur最初拖拽的图像就是我最初拖拽的图像。删除dragEnter处理程序后,我将无法再在面板中拖动图像。