Silverlight中实现拖拽功能

下面的示例演示如何在基于 Silverlight 的应用程序中拖放对象。出于安全考虑,不能在应用程序之间拖放对象。因此,说成在 Silverlight 插件区域内"滑动"对象更为准确。但是,术语"拖放"更为人知,因此在此处使用。

Xaml脚本:

< UserControl  x:Class ="DragAndDropSimple.Page"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"  
    Width
="400"  Height ="300" >
  
< Canvas  x:Name ="rootCanvas"
  Width
="640"
  Height
="480"
  Background
="Gray"
  
>
    
<!--  You can drag this rectangle around the canvas.  -->
    
< Rectangle
    
MouseLeftButtonDown ="Handle_MouseDown"
    MouseMove
="Handle_MouseMove"
    MouseLeftButtonUp
="Handle_MouseUp"
    Canvas.Left
="30"  Canvas.Top ="30"  Fill ="Red"
    Width
="50"  Height ="50"   />
  
</ Canvas >

</ UserControl >

后置代码:

//  Global variables used to keep track of the 
//  mouse position and whether the object is captured
//  by the mouse.
bool  isMouseCaptured;
double  mouseVerticalPosition;
double  mouseHorizontalPosition;

public   void  Handle_MouseDown ( object  sender, MouseEventArgs args) 
{
    Rectangle item 
=  sender  as  Rectangle;
    mouseVerticalPosition 
=  args.GetPosition( null ).Y;
    mouseHorizontalPosition 
=  args.GetPosition( null ).X;
    isMouseCaptured 
=   true ;
    item.CaptureMouse();
}

public   void  Handle_MouseMove( object  sender, MouseEventArgs args) 
{
    Rectangle item 
=  sender  as  Rectangle;
    
if  (isMouseCaptured) 
    {

        
//  Calculate the current position of the object.
         double  deltaV  =  args.GetPosition( null ).Y  -  mouseVerticalPosition;
        
double  deltaH  =  args.GetPosition( null ).X  -  mouseHorizontalPosition;
        
double  newTop  =  deltaV  +  ( double )item.GetValue(Canvas.TopProperty);
        
double  newLeft  =  deltaH  +  ( double )item.GetValue(Canvas.LeftProperty);

        
//  Set new position of object.
        item.SetValue(Canvas.TopProperty, newTop);
        item.SetValue(Canvas.LeftProperty, newLeft);

        
//  Update position global variables.
        mouseVerticalPosition  =  args.GetPosition( null ).Y;
        mouseHorizontalPosition 
=  args.GetPosition( null ).X;
    }
}

public   void  Handle_MouseUp( object  sender, MouseEventArgs args) 
{
    Rectangle item 
=  sender  as  Rectangle;
    isMouseCaptured 
=   false ;
    item.ReleaseMouseCapture();
    mouseVerticalPosition 
=   - 1 ;
    mouseHorizontalPosition 
=   - 1 ;
}

 

 

转载于:https://www.cnblogs.com/Dlonghow/archive/2008/12/12/1353693.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值