c# - 拖放移动控件而不是复制

标签 c# winforms

我有两个面板,其中一个在加载时填充了控件。当用户将控件拖到另一个面板时,它会将控件从原始面板移动到新面板,我宁愿复制该控件并将其放置在另一个面板中。我需要能够多次将同一个控件拖到面板中。我该如何实现呢?我曾尝试将拖动效果更改为复制,但这似乎并不能解决问题。

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/

相关文章:

c# - 如何使用动态 id 查找 ExtJS 元素

c# - TypeLoadException - 如何继续

c# - 提交 C# MapReduce 作业 Windows Azure HDInsight - 响应状态代码不表示成功 : 500 (Server Error)

c# - ProgressBar 在 Windows 窗体中很慢

c# - Web 应用程序模块化设计实践

c# - 按钮不会触发 Click 事件

c# - .NET WinForms 多线程行为 : Setting property value in ThreadPool. QueueUserWorkItem 尽管有异常

c# - WinForms:如何确定窗口是否不再处于事件状态(没有子窗口具有焦点)?

c# - Listview 选中的项目颜色变为灰色

c# - Windows 窗体应用程序中窗体加载期间触发的 SelectedValueChange() 事件