【问题标题】:Dragging and dropping a control from one form to another results in moving the control将控件从一个窗体拖放到另一个窗体会导致控件移动
【发布时间】:2009-10-14 13:46:21
【问题描述】:

我希望在将某个控件拖放到另一个表单时获得另一个副本。我的代码导致移动整个控件。鉴于我希望它们具有相同的引用,因为源每秒都会更新值,因此有没有办法让它们中的两个同时显示。

这是我的代码

    public partial class DragDropForm : Form
{
    public DragDropForm()
    {
        InitializeComponent();
    }

    private void tableLayoutPanel1_DragEnter(object sender, DragEventArgs e)
    {
        object data = e.Data.GetData(e.Data.GetFormats()[0]);
        if (data is GaugeContainer)
        {
            GaugeContainer gauge = data as GaugeContainer;
            tableLayoutPanel1.Controls.Add(gauge);
        }
        else if (data is DataGridView)
        {
            DataGridView table = data as DataGridView;
            tableLayoutPanel1.Controls.Add(table);

        }
    }

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



    // IN THE SOURCE FORM !!!!
    private void topCompaniesGridView_MouseDown(object sender, MouseEventArgs e)
    {
        this.DoDragDrop(this.topCompaniesGridView, DragDropEffects.Copy);
    }

【问题讨论】:

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


    【解决方案1】:

    一个控件一次只能放置在一个容器(窗体)上。您要做的是在目标窗体上创建控件的新实例。所以而不是:

    tableLayoutPanel1.Controls.Add(gauge);
    

    tableLayoutPanel1.Controls.Add(new GaugeContainer());
    // Bind to same data source as original control here...
    

    然后,您需要将控件绑定到与原始控件相同的数据源,当然前提是您有一个易于绑定的数据源。您可能在设计时设置的控件属性不会应用于新控件实例。您需要从原始表单的设计器文件中复制控件初始化代码。

    【讨论】:

      【解决方案2】:

      您可以通过创建一个相同大小的面板(我们称之为 B)并使用 VisualBrush 作为 B 的背景并将 A 设置为 Visual Brush 的 Visual 来显示一个控件(我们称之为 A)两次。

      但是,这是控件的惰性“图像”,不会响应输入等。

      更强大的方法是创建控件的另一个实例并将其绑定到与原始数据相同的基础数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        • 2012-12-03
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多