SL学习笔记之简单实现拖动2个元素自动合并
文笔不好,所以废话不多说,直奔主题了。
这里要实现的是一个拖动功能的附加功能,类似某购物网站把商品拖进购物车的功能
虽然之前js实现过,因为现在是学习sl,所以这里用sl实现。
步骤:
1.监听要拖动元素rect1的MouseLeftButtonUp、MouseMove、MouseLeftButtonDown事件
2.在MouseLeftButtonDown、MouseMove事件中实现拖动。
3.在MouseLeftButtonUp中实现临界合并
具体代码如下:
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>
后台代码
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;
}
}
代码非常简单