当前位置 : 主页 > 手机开发 > 无线 >

在wpf中移动任何控件

来源:互联网 收集:自由互联 发布时间:2021-06-10
我试图使用Canvas在wpf中移动控件 这是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 Can
我试图使用Canvas在wpf中移动控件

这是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;        
    }

代码正在运行,但当它移动时,控件会抖动.
什么是问题

当您调用GetPosition时,您应该使用DropCanvas作为参数而不是控件.你看到振动,因为TextBox一直在移动,你需要修复一些东西.

或者,您可以使用Expression Blend SDK中提供的MouseDragElementBehavior来移动容器中的对象.

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

网友评论