Moving any control in wpf

I am trying to move control to wpf using Canvas

This is 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>

and this is Code

    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 works, but when it moves, the control is shaking.
What is proplem

+5
source share
2 answers

When you call GetPosition, you should use DropCanvasas a parameter instead of a control. You see vibrations because the TextBox keeps moving and you need something fixed.

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

, : http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part-4

+6
    public void dragme(object sender, MouseButtonEventArgs e)
{
    if (_Move.IsChecked == true)
        db.Attach((DependencyObject)sender);

}

////MouseDragElementBehavior db;

 private void canvass_PreviewMouseDown(object sender, MouseButtonEventArgs e) 
{
if (_Move.IsChecked == true && filmgrid.Visibility == Visibility.Visible)// == true)  
        {
            filmgrid.PreviewMouseDown += new MouseButtonEventHandler(dragme); 
        }
0

All Articles