我有两个面板,其中一个在加载时填充了控件。当用户将控件拖到另一个面板时,它会将控件从原始面板移动到新面板,我宁愿复制该控件并将其放置在另一个面板中。我需要能够多次将同一个控件拖到面板中。我该如何实现呢?我曾尝试将拖动效果更改为复制,但这似乎并不能解决问题。
void panel_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
void panel_DragDrop(object sender, DragEventArgs e)
{
Button data = (Button)e.Data.GetData(typeof(Button));
FlowLayoutPanel _destination = (FlowLayoutPanel)sender;
FlowLayoutPanel _source = (FlowLayoutPanel)data.Parent;
if (_source != _destination)
{
// Add control to panel
data.Size = new Size(_destination.Width, 85);
_destination.Controls.Add(data);
// Reorder
Point p = _destination.PointToClient(new Point(e.X, e.Y));
var item = _destination.GetChildAtPoint(p);
int index = _destination.Controls.GetChildIndex(item, false);
_destination.Controls.SetChildIndex(data, index);
// Invalidate to paint!
_destination.Invalidate();
_source.Invalidate();
}
else
{
// Just add the control to the new panel.
// No need to remove from the other panel, this changes the Control.Parent property.
Point p = _destination.PointToClient(new Point(e.X, e.Y));
var item = _destination.GetChildAtPoint(p);
int index = _destination.Controls.GetChildIndex(item, false);
_destination.Controls.SetChildIndex(data, index);
_destination.Invalidate();
}
}
最佳答案
如果你想复制控件,那么你需要实际获取被复制控件的副本。执行此操作的最佳位置可能是将模式从移动更改为复制的地方。您可以将副本留在原始位置并继续移动原始位置,也可以移动副本。
所以你有:
Button data = (Button)e.Data.GetData(typeof(Button));
您需要克隆该按钮或创建一个新的 Button
并手动设置属性。克隆将是更好的解决方案。
关于c# - 拖放移动控件而不是复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085175/