Sheepy99 Sheepy99 - 21 days ago 4x
C# Question

Drag and drop event. Get the name of the control where the drag originated, whilst inside drop event method

I am attempting a drag and drop in WPF.

My program allows you to drag coloured labels around the screen, in essence giving you the effect that squares are being dragged and dropped.

Bearing in mind that only the text is dragged rather then the control itself (i.e. not the colour):

What I would like to achieve is that when the drop event fires, I can change the colour of the label which I dragged the text from.
After consulting MSDN I've failed to figure out how to get at the control in question and after plenty of trial and error I'm hoping somebody here can help.

Below is a sample of code which works, but the label who's colour I want to change is hard-coded, whereas in reality it could be any one of a number of labels.

private void ObjDrop(object sender, DragEventArgs e)
//testSquare is a hardcoded label
testSquare.Background = Brushes.LimeGreen;

//what I really need is for a variable to detect which label to access each time before I change its colour. So something along the lines of
Label myLabel = someCodeToGetTheLabelThatWasDragged;
myLabel.Background = Brushes.LimeGreen;


Hopefully I explained things well enough, thanks in advance.


You would use the IDataObject.GetData(Type) method to extract the the object in DragEventArgs.Data property. From there, you should be able to access whatever you store in the IDataObject.

This is a pretty general answer. To achieve said answer, that means you'll have to write your own class that implements IDataObject which contains the original control/control's name etc., then set the IDataObject when drag in initialized.

There may be an alternate solution available. I would watch what e.Data is in your current example, and try to work with that. If e.Data is of type Label, through casting, you could access the label that way, e.g. (e.Data as Label).Background = Brushes.LimeGreen;.

In a Drag and Drop implementation I've seen, the IDataObject contains the DropTarget and the DragSource, that way you can compare the two and allow/disallow things/types from being dragged and dropped by setting the Effect.