Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with GetDataPresent to let it accept all the derived types

I'm using drgevent.Data.GetDataPresent to determine whether the dragged component is acceptable or not.

I've got a problem which is that I want to accept a specific type say SomeType and all the types that derived from it. Seems GetDataPresent doesn't support such requirement.

Any idea?

like image 448
French Boy Avatar asked Sep 10 '11 08:09

French Boy


2 Answers

Just don't use GetDataPresent(), it is boilerplate but you're free to do it your way. Actually retrieve the object and check if you're happy with its type:

    protected override void OnDragEnter(DragEventArgs drgevent) {
        var obj = drgevent.Data.GetData(drgevent.Data.GetFormats()[0]);
        if (typeof(Base).IsAssignableFrom(obj.GetType())) {
            drgevent.Effect = DragDropEffects.Copy;
        }
    }

Where Base is the name of the base class. While the use of GetFormats() looks odd, this approach is guaranteed to work because dragging a .NET object only ever produces one format, the display name of the type of the object. Which is also the reason that GetDataPresent can't work for derived objects.

like image 184
Hans Passant Avatar answered Nov 06 '22 10:11

Hans Passant


I have answered a similar question previously: C# Drag and Drop - e.Data.GetData using a base class

What you can do is create a container class which holds the data that you are dragging. And then in the GetDataPresent you check for the container class type and if it is present then you can read the content member which contains the actual instance of your data.

Here is an quick example, if your base type is DragDropBaseData, you can create the following DragDropInfo class.

public class DragDropInfo 
{ 
  public DragDropBaseData Value { get; private set; } 

  public DragDropInfo(DragDropBaseData value) 
  { 
    this.Value= value; 
  } 
}

And then the drag drop can be initiated with the following, where DrafDropDerivedData is a class derived from DragDropBaseData.

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

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

e.Data.GetData(typeof(DragDropInfo)); 
like image 24
Chris Taylor Avatar answered Nov 06 '22 11:11

Chris Taylor