views:

30

answers:

1

Hi I need to move a multiple textboxes with a mouse cursor. I decided that I do it that way. If a textbox is clicked (and Control button is pressed) textbox is added to list of selected items. Then when button is still pressed and when mouse moves I do an operation of moving controls. However my code doesn't work well. Textboxes are moving but very very fast. Here is my code

 List<TextBox> items;
 private void txtBox_PreviewMouseDown(object sender, RoutedEventArgs e)
    {


            isClicked = true;
            startPoint = Mouse.GetPosition(  (sender as TextBox).Parent);
            items = CurrentSelection;




    }
private void txtBox_PreviewMouseMove(object sender, RoutedEventArgs e)
    {


        Point mousePos = Mouse.GetPosition(parentCanvas);
         if (isClicked)
         {
             foreach (TextBox item in items)
             {
                 double left = Canvas.GetLeft(item);
                 double top = Canvas.GetTop(item);

                 Canvas.SetLeft(item, left + (startPoint.X - mousePos.X));
                 Canvas.SetTop(item, top + (startPoint.Y - mousePos.Y));
             }
         }

    }

Basically I iterate through all selected items and change their position on canvas. However I probably calculate a new position in a wrong way.

+1  A: 

The problem is, that you always calculate the delta to the initial start point. You must actualize startPoint after every call to txtBox_PreviewMouseMove. Somethin like...

private void txtBox_PreviewMouseMove(object sender, RoutedEventArgs e) {  
    Point mousePos = Mouse.GetPosition(parentCanvas); 
     if (isClicked){ 
         foreach (TextBox item in items) { 
             double left = Canvas.GetLeft(item); 
             double top = Canvas.GetTop(item); 

             Canvas.SetLeft(item, left + (startPoint.X - mousePos.X)); 
             Canvas.SetTop(item, top + (startPoint.Y - mousePos.Y)); 
         } 
         startPoint=mousePoint;
     } 

} 

...should do the job. Another thing I have seen, is that the direction is probably inverted. This can be easily corrected. Change the calculcation to...

Canvas.SetLeft(item, left + (mousePos.X-startPoint.X ));  
Canvas.SetTop(item, top + (mousePos.Y-startPoint.Y));  

... and this problem should also be gone.

HCL
Thanks a lot :) It works
Berial