Reputation: 3459
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);
}
}
Upvotes: 2
Views: 14953
Reputation: 1505
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>
Upvotes: 4
Reputation: 29256
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.
Upvotes: 2
Reputation: 2298
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
Upvotes: 2