Drog和Drop TableLayoutPanel在面板中?

时间:2015-05-15 11:29:37

标签: c# .net winforms c#-4.0 drag-and-drop

我正在使用winforms / c#尝试拖拽面板中的tablelayoutpanel,tablelayout的拖动效果很好,但问题是tablelayoutpanel droped没有出现! 任何解决方案吗??

private void Registration_Load(object sender, EventArgs e)
{   
     panel2.AllowDrop = true;
     tableLayoutPanel1.AllowDrop = true;
     panel2.DragEnter += panel2_DragEnter;   
     panel2.DragDrop += panel2_DragDrop;
     tableLayoutPanel1.MouseDown += tableLayoutPanel1_MouseDown;
}   

private void panel2_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Move;
}

private void panel2_DragDrop(object sender, DragEventArgs e)
{
     ((TableLayoutPanel)e.Data.GetData(typeof(TableLayoutPanel))).Parent (Panel)sender;                
}
private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
{
     tableLayoutPanel1.DoDragDrop(tableLayoutPanel1, DragDropEffects.Move);
}

1 个答案:

答案 0 :(得分:0)

代码不足,您至少需要设置丢弃的TLP的Location属性,以确保它位于面板边界内和/或位于鼠标光标处。并且Z顺序很重要,设置Parent属性将其置于底部,以便它可以轻松地与面板中的其他控件重叠,您需要BringToFront()。

试试这个:

    private void panel2_DragEnter(object sender, DragEventArgs e) {
        if (e.Data.GetDataPresent(typeof(TableLayoutPanel))) e.Effect = DragDropEffects.Move;
    }

    private void panel2_DragDrop(object sender, DragEventArgs e) {
        var tlp = (TableLayoutPanel)e.Data.GetData(typeof(TableLayoutPanel));
        tlp.Location = panel2.PointToClient(new Point(e.X, e.Y));
        tlp.Parent = panel2;
        tlp.BringToFront();
    }