问题
I'm kind of new to WPF although I have some experience in Forms, and I decided to finally try to figure out how to use WPF. So When I got to draggable controls, this is the code I came up with (I attempted to change it to work with WPF but the control just twitches everywhere):
private void rectangle1_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed) {
double x = this.Left + (double)e.GetPosition(this).X - (double)rectangle1.Margin.Left;
double y = this.Top + (double)e.GetPosition(this).Y - (double)rectangle1.Margin.Top;
rectangle1.Margin = new Thickness(x, y, rectangle1.Margin.Right, rectangle1.Margin.Bottom);
}
}
回答1:
You want to use adorners to achieve dragging, resizing, rotating, etc.
回答2:
If you want to do it by hands use following algorithm:
- On
MouseDownevent: Save Mouse position, TopLeft position of control, and delta(offset) of these coordinates, and set some boolean field flag eg.IsDragStarttedto true. On
MouseMovecheck that drag started and use Mouse position and offset to calculate the new value of TopLeft position of controlOn
MouseUpevent setIsDragStarttedto false
回答3:
here is a pretty good article on the matter on MSDN. also, a quick search on Google revealse a veritable cornucopia of choices for you DnD dining pleasure.
来源:https://stackoverflow.com/questions/10022605/draggable-control-in-wpf