控件拖拽

1. 定义要用到的临时变量

        private bool dragging;
        Point mousePoint;
        TextBlock mouseCtrl = null;
        Rectangle shadow = new Rectangle();
        public MainWindow()
        {
            InitializeComponent();
            c.Children.Insert(0, shadow);
        }

 

2. 定义鼠标按下方法(索要拖拽控件的事件)

        private void button1_MouseDown(object sender, MouseButtonEventArgs e)
        {

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                dragging = true;
                mousePoint = e.GetPosition(this.c);
                mouseCtrl = (TextBlock)e.Source; 
                mouseCtrl.Visibility = Visibility.Collapsed;
                shadow.Width = mouseCtrl.Width;
                shadow.Height = mouseCtrl.Height;
                shadow.Fill = Brushes.Red;
                Canvas.SetLeft(shadow, Canvas.GetLeft(mouseCtrl));
                Canvas.SetTop(shadow, Canvas.GetTop(mouseCtrl));
                shadow.Visibility = Visibility.Visible;
                c.CaptureMouse();
            }   
        }

 

3. 定义鼠标移动方法(背景上定义)

        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
if (dragging) { if (e.LeftButton == MouseButtonState.Pressed) { Point theMousePoint = e.GetPosition(this.c); Console.WriteLine("Move: left:" + Canvas.GetLeft(mouseCtrl) + " top:" + Canvas.GetTop(mouseCtrl)); Canvas.SetLeft(shadow, theMousePoint.X - (mousePoint.X - Canvas.GetLeft(shadow))); Canvas.SetTop(shadow, theMousePoint.Y - (mousePoint.Y - Canvas.GetTop(shadow)));//简单的计算,只移动shadow mousePoint = theMousePoint; } } }

 

4. 定义鼠标松开方法

        private void button1_MouseUp(object sender, MouseButtonEventArgs e)
        {

            dragging = false;
            Mouse.Capture(null);
            shadow.Visibility = Visibility.Hidden;
            mouseCtrl.Visibility = Visibility.Visible;
            Canvas.SetLeft(mouseCtrl, Canvas.GetLeft(shadow));
            Canvas.SetTop(mouseCtrl, Canvas.GetTop(shadow));
        }

  

posted @ 2014-03-02 16:28  Alf7  阅读(214)  评论(0编辑  收藏  举报