Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving any control in wpf

Tags:

wpf

controls

I am trying to move control in wpf using Canvas

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>

and this is the 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 is working, but when it moves, the control shakes.
What is the proplem

like image 586
am shammout Avatar asked Apr 24 '12 12:04

am shammout


People also ask

How to move a control in WPF?

Answers. You need a Canvas panel to set the controls by position, and you need use the attached properties Canvas. SetTop and Canvas. SetLeft to move the controls.

How do I drag and drop in WPF?

In the drag source event handler, call the DoDragDrop method to initiate the drag-and-drop operation. In the DoDragDrop call, specify the drag source, the data to be transferred, and the allowed effects. Identify the element that will be a drop target. A drop target can be UIElement or a ContentElement.


1 Answers

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.

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

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

like image 104
Eli Arbel Avatar answered Sep 21 '22 21:09

Eli Arbel