开发者

moving multiple controls

开发者 https://www.devze.com 2023-01-11 21:06 出处:网络
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

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. H开发者_运维问答owever I probably calculate a new position in a wrong way.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消