我需要使用鼠标光标移动多个文本框。 我决定我这样做。 如果单击文本框(并按下控制按钮),则文本框将添加到所选项目列表中。然后,当仍然按下按钮并且鼠标移动时,我执行移动控件的操作。但是,我的代码无法正常运行。文本框正在移动,但是非常快。这是我的代码
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.
推荐答案问题是,您总是计算初始值的增量起点。您必须在每次调用txtBox _ PreviewMouseMove 之后实现startPoint。像这样的东西...
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.
更多推荐
移动多个控件
发布评论