Silverlight学习笔记(七)-----Silverlight事件处理之鼠标事件实现简单拖拽


XAML:只定义了一个矩形rectangle,要处理的事件有按下鼠标(左击)、鼠标移动、左击弹起。

 1 <UserControl x:Class="Event.MainPage"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6 mc:Ignorable="d"
7 d:DesignHeight="300" d:DesignWidth="400">
8
9 <Canvas x:Name="LayoutRoot" Width="640" Height="360" Background="BlueViolet">
10 <Rectangle x:Name="rect" Width="50" Height="50" Fill="Red"
11 MouseLeftButtonDown="rect_MouseLeftButtonDown"
12 MouseMove="rect_MouseMove"
13 MouseLeftButtonUp="rect_MouseLeftButtonUp"></Rectangle>
14 </Canvas>
15 </UserControl>



C#:注释

 1 public partial class MainPage : UserControl
2 {
3 public MainPage()
4 {
5 InitializeComponent();
6 }
7
8 bool isMouseCaptured;//是否捕获鼠标
9 double posV;
10 double posH;
11
12 private void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
13 {
14 Rectangle rect = sender as Rectangle;
15 //获取鼠标点击的position
16 posH = e.GetPosition(null).X;
17 posV = e.GetPosition(null).Y;
18 isMouseCaptured = true;
19 rect.CaptureMouse();//捕获
20 }
21
22 private void rect_MouseMove(object sender, MouseEventArgs e)
23 {
24 Rectangle rect = sender as Rectangle;
25 if (isMouseCaptured)
26 {
27 //鼠标移动的距离
28 double detalH = e.GetPosition(null).X - posH;
29 double detalV = e.GetPosition(null).Y - posV;
30 //新的坐标
31 double newH = detalH + (double)rect.GetValue(Canvas.LeftProperty);
32 double newV = detalV + (double)rect.GetValue(Canvas.TopProperty);
33 //设置矩形新位置
34 rect.SetValue(Canvas.TopProperty, newV);
35 rect.SetValue(Canvas.LeftProperty, newH);
36 //更新鼠标的position参数
37 posH = e.GetPosition(null).X;
38 posV = e.GetPosition(null).Y;
39 }
40 else { }
41 }
42
43 private void rect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
44 {
45 Rectangle rect = sender as Rectangle;
46 //释放鼠标
47 isMouseCaptured = false;
48 rect.ReleaseMouseCapture();
49 posH = -1;
50 posV = -1;
51 }
52 }



效果图:无动态图





----------------------------------------------完----------------------------------------------------

posted @ 2012-01-31 15:52  Nereus_37  阅读(1245)  评论(1编辑  收藏  举报