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);
}
}
You want to use adorners to achieve dragging, resizing, rotating, etc.
Alternative:
Microsoft.Xaml.Behaviors.Wpf
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
<Grid>
<behaviors:Interaction.Behaviors>
<behaviors:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</behaviors:Interaction.Behaviors>
</Grid>
If you want to do it by hands use following algorithm:
MouseDown
event: Save Mouse position , TopLeft position of control, and delta(offset) of these coordinates, and set some boolean field flag eg. IsDragStartted
to true. On MouseMove
check that drag started and use Mouse position and offset to calculate the new value of TopLeft position of control
On MouseUp
event set IsDragStartted
to false
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.