Oztaco
Oztaco

Reputation: 3459

Draggable control in WPF?

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

Answers (4)

Konstantin S.
Konstantin S.

Reputation: 1505

Alternative:

  1. Install NuGet package: Microsoft.Xaml.Behaviors.Wpf
  2. Add this to root element:
xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"
  1. And just place this inside your element:
<Grid>
    <behaviors:Interaction.Behaviors>
        <behaviors:MouseDragElementBehavior ConstrainToParentBounds="True"/>
    </behaviors:Interaction.Behaviors>
</Grid>

Upvotes: 4

Muad&#39;Dib
Muad&#39;Dib

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

asktomsk
asktomsk

Reputation: 2298

If you want to do it by hands use following algorithm:

  1. On 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.
  2. On MouseMove check that drag started and use Mouse position and offset to calculate the new value of TopLeft position of control

  3. On MouseUp event set IsDragStartted to false

Upvotes: 2

K Mehta
K Mehta

Reputation: 10553

You want to use adorners to achieve dragging, resizing, rotating, etc.

Upvotes: 7

Related Questions