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 sp开发者_如何转开发ecific 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));
I had a similar problem. I want it to use DragDrop only with interfaces, which doesn't work ether. So I put my data in to an array of object.
DoDragDrop(_dragDropSource, new[] { _dragDropSource.DataContext }, DragDropEffects.Move);
if (((object[]) e.Data.GetData(typeof(object[])))?[0] is ICatTreeViewGroup group) {
// do something with a group
}
精彩评论