Silverlight 2 Study Notes for the perfect journey
The drag and drop effect can be divided into three steps
- Press the mouse to trigger the mouseleftbuttondown event and select the object to be dragged.
- Move the mouse, trigger the mousemove event, and move the selected object
- Open the mouse, trigger the mouseleftbuttonup event, and stop capturing events.
PageCode:
< Usercontrol X : Class = "Silverlightstuding. mousedrag" Xmlns = Http://schemas.microsoft.com/winfx/2006/xaml/presentation" Xmlns : X =Http://schemas.microsoft.com/winfx/2006/xaml" Width = "400" Height = "300" > < Canvas > < Stackpanel Mouseleftbuttondown = "Stackpanel_mouseleftbuttondown" Mousemove = "Stackpanel_mousemove" Mouseleftbuttonup = "Stackpanel_mouseleftbuttonup" Canvas . Left = "50" Canvas . Top = "50" Width = "200" Height = "80" > < Border Borderthickness = "3" Borderbrush = "Red" > < Stackpanel Orientation = "Horizontal" Verticalalignment = "Center" Horizontalalignment = "Center" > < Image Source = "Drag.png" /> < Textblock Text = "Drag Me" Verticalalignment = "Center" Margin = "10" > </ Textblock > </ Stackpanel > </ Border > </ Stackpanel > < Textblock Text = "" X : Name = "Txtstatus" Canvas . Top = "200" Canvas . Left = "60" > </ Textblock > </ Canvas > </ Usercontrol >
Start the drag-and-drop operation to handle the mouseleftbuttondown event
Private VoidStackpanel_mouseleftbuttondown (ObjectSender, mousebuttoneventargs e) {frameworkelement element = senderAsFrameworkelement; mouseposition = E. getposition (Null); Trackingmousemove =True;If(Null! = Element) {element. capturemouse (); element. cursor = cursors. Hand;} txtstatus. Text ="Mouseleftbuttondown";}
Move objects to implement mousemove event processingProgram, Calculates and updates the position of the element, and updates the position of the mouse.
Private Void Stackpanel_mousemove ( Object Sender, mouseeventargs e) {frameworkelement element = sender As Frameworkelement; If (Trackingmousemove ){ Double DeltaV = E. getposition ( Null ). Y-mouseposition. Y; Double Deltah = E. getposition ( Null ). X-mouseposition. X; Double Newtop = DeltaV + (Double ) Element. getvalue (canvas. topproperty ); Double Newleft = deltah + ( Double ) Element. getvalue (canvas. leftproperty); element. setvalue (canvas. topproperty, newtop); element. setvalue (canvas. leftproperty, newleft); mouseposition = E. getposition ( Null );} Txtstatus. Text =" Mouse moving ...... ";}
Drag and Drop to release the mouse and implement the mouseleftbuttonup event handler.
private void stackpanel_mouseleftbuttonup ( Object sender, mousebuttoneventargs E) {frameworkelement element = sender as frameworkelement; trackingmousemove = false ; element. releasemousecapture (); mouseposition. X = mouseposition. y = 0; element. cursor = null ; txtstatus. TEXT = " releasemouse " ;}