Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Drag and Drop WPF Controls

0.00/5 (No votes)
27 Jul 2013 1  
This tip is about how to make our WPF controls moveable at runtime

Introduction

I was looking for a solution to make a Form Generator application with WPF. But my big problem was "How can I move my controls by user's mouse events on the Grid or other container controls".

I've searched a lot on the internet, but none of my search results helped me. Finally, I found how Canvas control and its properties can be helpful. And with using Canvas control, I created my own FormGenerator app.

Using the Code

As I said, to be able to move an object with mouse or other input devices at run time, we can use a Canvas control. When you add a control (like Button) to a Canvas, this control gets some properties that all of them are depending on the Canvas control. Properties like Canvas.Left and Canvas.Right.

With these properties, we can move an object (control) where we want on its parent (Canvas). To do this, we should have three events: MouseLeftButtonDown, MouseMove, and MouseLeftButtonUp. In some components, the MouseLeftButtonDown doesn't fire because of that, I used the PreviewMouseLeftButtonDown.

The MouseLeftButtonDown event code is like this:

private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{     
    //In this event, we get current mouse position on the control to use it in the MouseMove event.
    FirstXPos = e.GetPosition(sender as Control).X;
    FirstYPos = e.GetPosition(sender as Control).Y;
    FirstArrowXPos = e.GetPosition((sender as Control).Parent as Control).X - FirstXPos;
    FirstArrowYPos = e.GetPosition((sender as Control).Parent as Control).Y - FirstYPos;
    MovingObject = sender;
}

The MouseLeftButtonUp event code is like this:

void PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{  
    MovingObject = null;
}

And our main event, "MouseMove", is like this:

private void MouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        (MovingObject as FrameworkElement).SetValue(Canvas.LeftProperty,
             e.GetPosition((MovingObject as FrameworkElement).Parent as FrameworkElement).X - FirstXPos);

        (MovingObject as FrameworkElement).SetValue(Canvas.TopProperty,
             e.GetPosition((MovingObject as FrameworkElement).Parent as FrameworkElement).Y - FirstYPos);
    }
}

Finally

I hope this tip helps you to solve your possibility problems with drag and drop in WPF.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here