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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With