C# Drag and Drop - e.Data.GetData using a base class

你离开我真会死。 提交于 2019-12-08 17:21:09

问题


I am using C# and Winforms 3.5

I have a list of user controls all derived from one base class. These controls can be added to various panels and I'm trying to implement the drag-drop functionality, the problem I'm running in to is on the DragDrop event.

For DragEventArgs e.Data.GetData(typeof(baseClass)) doesn't work. It wants:

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

Is there a way I can get around this, or a better way to architect it?


回答1:


You can wrap the data in a common class. For example, assuming your base class is called DragDropBaseControl

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

  public DragDropInfo(DragDropBaseControl control)
  {
    this.Control = control;
  }
}

And then the drag drop can be initiated with the following in the base class

DoDragDrop(new DragDropInfo(this), DragDropEffects.All);

And you can access the data in the drag events using the following

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

Have I understood your requirement correctly?




回答2:


To get the dragged object dynamically, without even knowing its type or its base type, I use this code inside the DragDrop event:

baseClass myObject = (baseClass)e.Data.GetData(e.Data.GetFormats()[0]);

as e.Data.GetFormats()[0] will always hold string representation of the type of the dragged object.

Note that I assumed there's one object was dragged but the idea is the same for multiple dragged objects.




回答3:


To elaborate on Abdulhameed Shalabi's answer, make sure the object is of the type expected; otherwise an exception will be thrown on the attempt to cast.

One way is a simple try-catch and ignore the drag-drop if the try fails.

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


来源:https://stackoverflow.com/questions/2731425/c-sharp-drag-and-drop-e-data-getdata-using-a-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!