拖放移动错误的面板

时间:2014-05-07 12:25:13

标签: c#

我正在开发一个包含多个面板的项目。我在表格顶部有6个面板,在这两个面板下面有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;
    }

1 个答案:

答案 0 :(得分:1)

我认为您希望在MouseDown事件中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;
}