C#拖放 - 使用基类的e.Data.GetData

Dus*_*oks 7 c# drag-and-drop winforms

我正在使用C#和Winforms 3.5

我有一个用户控件列表,所有用户控件都派生自一个基类.这些控件可以添加到各种面板中,我正在尝试实现拖放功能,我正在运行的问题是在DragDrop事件上.

对于DragEventArgs e.Data.GetData(typeof(baseClass))不起作用.它想要:

e.Data.GetData(typeof(derivedClass1))
e.Data.GetData(typeof(derivedClass2))
etc...
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题,或者更好的方法来构建它?

Chr*_*lor 17

您可以将数据包装在公共类中.例如,假设您的基类名为DragDropBaseControl

public class DragDropInfo
{
  public DragDropBaseControl Control { get; private set; }

  public DragDropInfo(DragDropBaseControl control)
  {
    this.Control = control;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后可以使用基类中的以下内容启动拖放

DoDragDrop(new DragDropInfo(this), DragDropEffects.All);
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法访问拖动事件中的数据

e.Data.GetData(typeof(DragDropInfo));
Run Code Online (Sandbox Code Playgroud)

我是否正确理解了您的要求?