SL学习笔记之简单实现拖动2个元素自动合并

 

 

 

文笔不好,所以废话不多说,直奔主题了。

这里要实现的是一个拖动功能的附加功能,类似某购物网站把商品拖进购物车的功能

虽然之前js实现过,因为现在是学习sl,所以这里用sl实现。

步骤:

1.监听要拖动元素rect1的MouseLeftButtonUp、MouseMove、MouseLeftButtonDown事件

2.在MouseLeftButtonDown、MouseMove事件中实现拖动。

3.在MouseLeftButtonUp中实现临界合并

具体代码如下:

ContractedBlock.gif ExpandedBlockStart.gif xaml代码
 
   
< Canvas Background = " #1f2345 " >
< Rectangle x:Name = " rect1 " MouseLeftButtonDown = " rect1_MouseLeftButtonDown " Canvas.Left = " 50 " Canvas.Top = " 50 " MouseMove = " rect1_MouseMove " MouseLeftButtonUp = " rect1_MouseLeftButtonUp " RadiusX = " 8 " RadiusY = " 8 " Width = " 200 " Height = " 200 " Fill = " Black " Margin = " 0,0,200,0 " >
</ Rectangle >
< Rectangle x:Name = " rect2 " Canvas.Left = " 500 " Canvas.Top = " 50 " RadiusX = " 8 " RadiusY = " 8 " Width = " 200 " Height = " 200 " Fill = " Red " >
</ Rectangle >
</ Canvas >

 

ContractedBlock.gif ExpandedBlockStart.gif 后台代码
 
   
Point movePoint;
Point oriPosition;
bool isMoving = false ;
private void rect1_MouseLeftButtonDown( object sender, MouseButtonEventArgs e)
{
FrameworkElement element
= sender as FrameworkElement;
if (element != null )
{
movePoint
= oriPosition = e.GetPosition( null );
isMoving
= true ;
element.CaptureMouse();
element.Cursor
= Cursors.Hand;
Canvas.SetZIndex(element,
1 );
}
}
private void rect1_MouseMove( object sender, MouseEventArgs e)
{
if (isMoving)
{
FrameworkElement element
= sender as FrameworkElement;
Point currPoint
= e.GetPosition( null );
double deltaY = currPoint.Y - movePoint.Y;
double deltaX = currPoint.X - movePoint.X;
double x = Canvas.GetTop(element);
double newTop = deltaY + Canvas.GetTop(element);
double newLeft = deltaX + Canvas.GetLeft(element);
Canvas.SetLeft(element, newLeft);
Canvas.SetTop(element, newTop);
movePoint
= currPoint;

}
}

private void rect1_MouseLeftButtonUp( object sender, MouseButtonEventArgs e)
{
double left2 = Canvas.GetLeft(rect2);
double top2 = Canvas.GetTop(rect2);
Rect rectRight
= new Rect(left2, top2, rect2.Width, rect2.Height);

double left = Canvas.GetLeft(rect1);
double top = Canvas.GetTop(rect1);
Rect rectLeft
= new Rect(left, top, rect1.Width, rect1.Height);
// 我在这里看到了ae的影子
rectRight.Intersect(rectLeft);
if (rectRight.IsEmpty)
{
isMoving
= false ;
rect1.ReleaseMouseCapture();
}
else
{

Canvas.SetLeft(rect1, left2);
Canvas.SetTop(rect1, top2);

Canvas.SetZIndex(rect1,
2 );
Canvas.SetZIndex(rect2,
1 );

rect2.Fill
= new SolidColorBrush(
Color.FromArgb(
100 ,
(
byte ) new Random().Next( 0 , 254 ),
(
byte ) new Random().Next( 0 , 254 ), ( byte ) new Random().Next( 0 , 254 )));
isMoving
= false ;
}
}

 

 

代码非常简单

转载于:https://www.cnblogs.com/fairy-tale/archive/2009/12/07/1618471.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值