Silverlight学習ノート(7)---Silverlightイベント処理のマウスイベントを簡単にドラッグ&ドロップ

10970 ワード

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 }

効果図:ダイナミックマップなし
Silverlight学习笔记(七)-----Silverlight事件处理之鼠标事件实现简单拖拽----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------