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

C#使用基类拖放-e.Data.GetData,c#,winforms,drag-and-drop,C#,Winforms,Drag And Drop,我正在使用C#和Winforms 3.5 我有一个从一个基类派生的用户控件列表。这些控件可以添加到各种面板中,我正在尝试实现拖放功能,我遇到的问题是DragDrop事件 对于DragEventArgse.Data.GetData(typeof(baseClass))不起作用。它希望: e.Data.GetData(typeof(derivedClass1)) e.Data.GetData(typeof(derivedClass2)) etc... 有什么方法可以绕过这个问题,或者有更好的方法来

我正在使用C#和Winforms 3.5

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

对于DragEventArgs
e.Data.GetData(typeof(baseClass))
不起作用。它希望:

e.Data.GetData(typeof(derivedClass1))
e.Data.GetData(typeof(derivedClass2))
etc...

有什么方法可以绕过这个问题,或者有更好的方法来构建它吗?

您可以将数据包装到一个公共类中。例如,假设您的基类称为DragDropBaseControl

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

  public DragDropInfo(DragDropBaseControl control)
  {
    this.Control = control;
  }
}
然后,可以在基类中使用以下命令启动拖放

DoDragDrop(new DragDropInfo(this), DragDropEffects.All);
您可以使用以下命令访问拖动事件中的数据

e.Data.GetData(typeof(DragDropInfo));

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

要动态获取拖动对象,甚至不知道其类型或基本类型,我在
DragDrop
事件中使用以下代码:

baseClass myObject = (baseClass)e.Data.GetData(e.Data.GetFormats()[0]);
as
e.Data.GetFormats()[0]
将始终保持拖动对象类型的字符串表示形式


请注意,我假设拖动了一个对象,但多个拖动对象的想法是相同的。

要详细说明Abdulhameed Shalabi的答案,请确保该对象是预期的类型;否则,在尝试强制转换时将引发异常

一种方法是简单的try-catch,如果尝试失败,则忽略拖放

try {
    baseClass item = (baseClass)e.Data.GetData( e.Data.GetFormats( )[0] );
    if (item != null ) { do stuff }
} catch { }

有一个交互界面可以帮助你吗?不,一个界面不会改变任何东西。我会尝试一下,然后回来,但它看起来很有希望。