在wpf中移动任何控件 [英] moving any control in wpf

查看:226
本文介绍了在wpf中移动任何控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Canvas

这是 XAML

This is the XAML

    <Canvas Grid.Column="1" Grid.Row="0" x:Name="DropCanvas"   AllowDrop="True"  DragOver="DropCanvas_DragOver" 
            Drop="Canvas_Drop" DragEnter="Canvas_DragEnter" Background="#12000000" >
        <TextBox Canvas.Left="162" Canvas.Top="188" Height="23" Name="textBox1" Width="120"  
                 PreviewMouseMove="textBox1_PreviewMouseMove" 
                 PreviewMouseLeftButtonDown="textBox1_PreviewMouseLeftButtonDown" 
                 PreviewMouseUp="textBox1_PreviewMouseUp" />
    </Canvas>

这是代码

    Point p = new Point();
    private void textBox1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Control control = sender as Control;

        control.CaptureMouse();
        p = e.GetPosition(control);   
    }

    private void textBox1_PreviewMouseMove(object sender, MouseEventArgs e)
    {       
            Control control = sender as Control;
            Point x = e.GetPosition(control);
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Canvas.SetLeft(control, Canvas.GetLeft(control) + (x.X - p.X));
                Canvas.SetTop(control, Canvas.GetTop(control) + (x.Y - p.Y));
            }
            p = x;          
    }

    private void textBox1_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        Control control = sender as Control;
        control.ReleaseMouseCapture();

        activated = false;        
    }

代码可以正常工作,但是当它移动时,控件就会晃动。

有什么问题

The code is working, but when it moves, the control shakes.
What is the proplem

推荐答案

调用 GetPosition 您应该使用 DropCanvas 作为参数而不是控件。您会看到振动,因为TextBox一直在移动,需要固定的东西。

When you call GetPosition you should use DropCanvas as the parameter instead of the control. You're seeing vibrations because the TextBox keeps moving and you need something fixed.

或者,您可以使用 MouseDragElementBehavior 在Expression Blend SDK中可用,以移动容器中的对象。

Alternatively, you can use the MouseDragElementBehavior available in Expression Blend SDK to move objects in a container.

此外,该项目对您也很有用: http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part-4

Also, this project can be useful to you: http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part-4

这篇关于在wpf中移动任何控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆