SilverLight的使用可以帮助开发人员轻松的解决一些以前爱只能依靠美工才能解决的相关开发问题。现在我们将会学到其中的一个使用技巧,就是SilverLight拖动的实现方式。#t#
SilverLight拖动前台代码:
- < UserControl
- xmlns="http://schemas.microsoft.
com/winfx/2006/xaml/presentation" - xmlns:x="http://schemas.
microsoft.com/winfx/2006/xaml" - x:Class="SilverlightApplic
ation6.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>
SilverLight拖动后台代码:
- 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();
- mousePositionmousePosition.X =
mousePosition.Y = 0;- element.Cursor = null;
- }
- }
- }
以上就是对SilverLight拖动相关实现方法做得具体介绍。