Search code examples
c#wpfdata-objects

DataObject.GetDatapresent with subclass


When I call this method DataObject.GetData(typeof(ItemType)) from an instance of a subclass of ItemType the method returns null... How can i get the data from the subtype? Thank you


Solution

  • The DataObject handling doesn't deal with class hierarchies - it's a straight string 'type' derived from the full name of the data type given, so it has no context to provide it the knowledge of subclasses. I've just hit up against exactly the same problem implementing drag and drop in a treeview.

    I had two options (these are possibly drag and drop-specific - if that's not your problem, it may not be a whole lot of use) - both rely on changing the source of the data object (again, if you don't have access to that, it may not be much use).

    1. Create a wrapper class which takes an ItemType instance, and when calling DoDragDrop, pass that wrapper instead of the actual instance. On the other side, test for DataObject.GetData(typeof(WrapperClass)) instead.

    2. Again, where the data object is being set, set a DataObject instance yourself - eg. call

      ctl.DoDragDrop(new DataObject(typeof(ItemType).FullName, itemTypeInstance),
          DragDropEffects.Move|DragDropEffects.Copy)
      

      then you can just use DataObject.GetData(typeof(ItemType)) on the other side.