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

我正在使用C#和Winforms 3.5

我有一个用户控件列表,所有用户控件都派生自一个基类。 这些控件可以添加到各种面板中,我正在尝试实现拖放function,我正在运行的问题是在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]); 

因为e.Data.GetFormats()[0]将始终保持拖动对象类型的字符串表示forms。

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