Drag-and-drop operations have two aspects: source and target. To create a drag-and-drop source, you must call the dragdrop. dodragdrop () method at a certain position to initialize the drag-and-drop operation. In this case, determine the source of the drag operation, hold the content to be moved, and specify the appropriate drag-and-drop effect (copy, move, etc ).
The dodragdrop () method is usually called in response to the previewmousedown or mousedown event.
The received element must set its allowdrop attribute to true and process data by processing the drop event.
Front-end code:
<Grid>
<Grid. rowdefinitions>
<Rowdefinition Height = "*"> </rowdefinition>
<Rowdefinition Height = "*"> </rowdefinition>
</Grid. rowdefinitions>
<Grid. columndefinitions>
<Columndefinition width = "*"> </columndefinition>
<Columndefinition width = "*"> </columndefinition>
</Grid. columndefinitions>
<Textbox name = "Source" grid. Row = "0" background = "Purple" foreground = "white" mousedown = "source_mousedown"> blog site: www.cnblogs.com </textbox>
<Image Source = "http://static.cnblogs.com/images/logo_small.gif" grid. Column = "1" stretch = "NONE" mousedown = "image_mousedown"> </image>
<Label name = "target" grid. Row = "1" background = "yellowgreen" allowdrop = "true" Drop = "ondrop"> drag the text here </label>
<Image name = "targetimg" grid. row = "1" grid. column = "1" allowdrop = "true" Drop = "targetimg_drop_1" stretch = "NONE" Source = "http://www.baidu.com/img/baidu_sylogo1.gif"> </image>
</GRID>
Background code:
/// <Summary>
/// Source data
/// </Summary>
Private void source_mousedown (Object sender, mousebuttoneventargs E)
{
Textbox objtext = sender as textbox;
Dragdrop. dodragdrop (objtext, objtext, dragdropeffects. copy );
}
/// <Summary>
/// Image source data
/// </Summary>
Private void image_mousedown (Object sender, mousebuttoneventargs E)
{
Image objimage = sender as image;
Dragdrop. dodragdrop (objimage, objimage. Source, dragdropeffects. copy );
}
/// <Summary>
/// Target location
/// </Summary>
Private void ondrop (Object sender, drageventargs E)
{
If (E. Data. getdatapresent (dataformats. Text ))
E. effects = dragdropeffects. copy;
Else
Return;
This.tar get. content = E. Data. getdata (dataformats. Text );
}
Private void targetimg_drop_1 (Object sender, drageventargs E)
{
E. Data. getformats ();
If (E. Data. getdatapresent ("system. Windows. Media. imaging. bitmapframedecode "))
E. effects = dragdropeffects. copy;
Else
{
Return;
}
// Targetimg. Source = (imagesource) E. Data. getdata ("system. Windows. Media. imaging. bitmapframedecode ");
(Image) sender). Source = (imagesource) E. Data. getdata ("system. Windows. Media. imaging. bitmapframedecode ");
}
If you do not know the Data Type of the drag-and-drop source data, you can use the getformats () method that implements the idataobject interface. E. Data. getformats (); Data implements the idataobject interface.