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)
{
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.