SilverLight实现拖动代码
前台代码:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightApplication6.Page"
Width="640" Height="480">
<Canvas x:Name="LayoutRoot" Background="White">
<Image Margin="263,185,249,167" Source="1.png" Stretch="Fill" MouseLeftButtonDown="Image_MouseLeftButtonDown"
MouseMove="Image_MouseMove"
MouseLeftButtonUp="Image_MouseLeftButtonUp"/>
</Canvas>
</UserControl>
后台代码:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication6
{
public partial class Page : UserControl
{
bool trackingMouseMove = false;
Point mousePosition;
public Page()
{
// 需要初始化变量
InitializeComponent();
}
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
mousePosition = e.GetPosition(null);
trackingMouseMove = true;
if (null != element)
{
element.CaptureMouse();
element.Cursor = Cursors.Hand;
}
}
private void Image_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);
}
}
private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
trackingMouseMove = false;
element.ReleaseMouseCapture();
mousePosition.X = mousePosition.Y = 0;
element.Cursor = null;
}
}
}