Silverlight实例开发 简单的拖拽效果

Silverlight 2完美征程学习笔记

拖拽效果分为3个步骤

  1. 按下鼠标,触发MouseLeftButtonDown事件,选择要拖动的对象
  2. 移动鼠标,触发MouseMove事件,移动选择的对象
  3. 放开鼠标,触发MouseLeftButtonUp事件,停止捕捉事件

页面代码:

<UserControl x:Class="SilverlightStuding.MouseDrag"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Canvas>
        <StackPanel MouseLeftButtonDown="StackPanel_MouseLeftButtonDown" MouseMove="StackPanel_MouseMove" 
                MouseLeftButtonUp="StackPanel_MouseLeftButtonUp" Canvas.Left="50" Canvas.Top="50" Width="200" Height="80">
        <Border BorderThickness="3" BorderBrush="Red">
            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                <Image Source="drag.png"/>
                <TextBlock Text="Drag Me" VerticalAlignment="Center" Margin="10">
   TextBlock>
             StackPanel>  Border>  StackPanel> <TextBlock Text="" x:Name="txtStatus" Canvas.Top="200" Canvas.Left="60"> TextBlock>  Canvas>  UserControl>

 

开始拖放操作,实现MouseLeftButtonDown事件的处理

        private void StackPanel_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;
            }
            txtStatus.Text = "MouseLeftButtonDown";
        }

移动对象,实现 MouseMove事件处理程序,计算元素的位置并更新,同时更新鼠标的位置

        private void StackPanel_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);
            }

            txtStatus.Text = "Mouse Moving ……";
        }

 

完成拖放操作,释放鼠标,实现MouseLeftButtonUp事件处理程序

        private void StackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            trackingMouseMove = false;
            element.ReleaseMouseCapture();

            mousePosition.X = mousePosition.Y = 0;
            element.Cursor = null;

            txtStatus.Text = "ReleaseMouse";
        }

你可能感兴趣的:(Silverlight实例开发 简单的拖拽效果)